I want to ask the user for 2 inputs, first name and last name, return a greeting and store the names in a Dictionary with the Keys being 'FName' and 'LName'
The following stores the greeting fine....
def name():
d = {}
x = input('Please enter your first name: ')
y = input('Please enter your last name: ')
d = {}
d[x] = y
print("Hello", x, y)
print(d)
name()
but I am not sure how to get the key/values in the dictionary properly. Right now it stores the equivalent of:
{'Joe': 'Smith'}
I know I need to reformat the following line different I am just not sure how to approach it...
d[x] = y
You'll want to manually set the keys you are storing against
d['FName'] = x
d['LName'] = y
Or more simply
d = {
'FName': x,
'LName': y
}
Here is another example:
def name():
d = {}
qs = dict(Fname='first name', Lname='last name')
for k,v in qs.items():
d[k] = input('Please enter your {}: '.format(v))
return d
name()
Nevermind, I figured it out. Sorry.
d['Fname'] = x
d['Lname'] = y
Related
So I wrote this code with the help of Stack Overflow users that transfers points to an individual based on whether "++" or "--" appears behind an individual.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if '->' in s:
names = s.split('->')
g[names[1]] = g[names[0]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x:g[x] for x in g if g[x] != 0}
print(keep(["Jim++", "John--", "Jeff++", "Jim++", "John--", "John->Jeff",
"Jeff--", "June++", "Home->House"]))
So most of the program is alright, however, when I put "Home->House" into it, it returns a KeyError. I kinda understand why it does that, but I'm clueless as to how to fix that...
I tried browsing the internet for solutions but all they recommended was to use .get(), which doesn't really help me solve the issue.
How can I make my output just neglect if like an element doesn't have "++" or "--" in it... like how can I make sure if an input is just "Jim" instead of "Jim++" or "Jim--", the function would just neglect it...
So in my example, if the input for keep is
["Jim++", "John--", "Jeff++", "Jim++", "John--", "John->Jeff", "Jeff--", "June++", "Home->House "]
the output would be
{'Jeff': -2, 'June': 1, 'Jim': 2}
instead of KeyError
You get KeyError because g[names[1]] = g[names[0]] is trying to access element in dictionary that isn't there. You get the same issue with simple print(keep(["John->Jeff"])), because there are no ++ or -- actions executed first to initialise those keys ("John" and "Jeff" in g
Based on your desired output you want to ignore such actions that are for non existing keys.
Add if names[1] in g and names[0] in g: into your keep implementation i.e.
Edit: also g[names[1]] = g[names[0]] needs to change to g[names[1]] += g[names[0]] to product correct outcome.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if "->" in s:
names = s.split("->")
if names[1] in g and names[0] in g:
g[names[1]] += g[names[0]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x: g[x] for x in g if g[x] != 0}
In your code, when you get Home->House, it's the first appearence of both the keys. That's why you get KeyError when you try to execute g[names[1] = g[names[0]]: g[names[0]] is g['Home'], but this entry doesn't exist in your dict. You can simply solve swapping the order of the lines:
if '->' in s:
names = s.split('->')
g[names[0]] = 0
g[names[1]] = g[names[0]]
To neglect strings which haven't the "++" or the "--", you can simply add an if before performing get_name(s):
else:
if '++' in s or '--' in s:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
This code returns the expected output
Your code actually does ignore examples which do not include "++" or "--" in the else-section of your function.
The KeyError occurs because neither "Home" nor "House" appear in the List of input strings before you try to move the entry of "Home" into the entry of "House". Because the keys "Home" and "House" are not in your dictionary g you get a KeyError.
Below is a solution which does what you want.
def get_name(input):
return input.replace("+", "").replace("-", "")
def keep(actions: list):
g = {}
for s in actions:
if '->' in s:
names = s.split('->')
if names[0] in g.keys() and names[1] in g.keys():
g[names[1]] = g[names[0]] + g[names[1]]
g[names[0]] = 0
else:
name = get_name(s)
if name not in g:
g[name] = 0
if "++" in s:
g[name] += 1
if "--" in s:
g[name] -= 1
return {x:g[x] for x in g if g[x] != 0}
print(keep(["Jim++", "John--", "Jeff++", "Jim++", "John", "John--", "John->Jeff",
"Jeff--", "June++", "Home->House"]))
I added a check to make sure the keys exist in dict d when the input string includes a "->".
In order to get the output you indicated in your question, which includes 'Jeff': -2, you also need to make sure to add the value of the original key to the value of the new key. This is done in line
g[names[1]] = g[names[0]] + g[names[1]]
Otherwise the output will say 'Jeff': -3 as the input string "Jeff++" will be ignored.
What I want is to reorder this '01110100' by a key 41325768 ,
the expected result: 11100010 , code result:10110010.
def perm(block, key):
block = list(block)
key = list(map(int, str(key))) # converting key to list
key = [x - 1 for x in key] # subtracting 1 from each (zero based)
new_key = [key[i] for i in key]
block = [block[i] for i in new_key]
block = "".join(block)
return block
so I added this line new_key = [key[i] for i in key] to fix the issue but the result so close:11100100
No idea what to do to fix it...😥
The difference between what you want and what you have is the difference in interpretation of the key. For example regarding the "4" at the start of your key, you want that to mean "put the first character in 4th position" but it's being used to say "take the first character from the fourth position".
You can change to the intended action by
def perm(block, key):
new_block = [" "]*len(key)
for ix, kval in enumerate(key):
new_block[int(kval)-1] = block[ix]
return "".join(new_block)
keyc = input('Permutation key: ')
plain = input('String to encode: ')
print ('\nResult: ', perm(str(plain),str(keyc)))
Input/output:
Permutation key: 41325768
String to encode: 01110100
Result: 11100010
I think I understood what means but your approach is wrong, here is a simple version of your code I made.
bi_s = '01110100'
key_s = '41325768'
new_bi = ''
bi_list = list(map(int, str(bi_s)))
key_list = list(map(int, str(key_s)))
print("The New Key")
for i in key_list:
# print(bi_list[i-1], end='', flush=True)
new_bi += str(bi_list[i-1])
print(new_bi)
print("The Origin Key")
for i in bi_list:
print(i, end='', flush=True)
the output :
The New Key
10110010
The Origin Key
01110100
Trying to figure out how to work a list of user input integers into separate categories and adding those categories together, and I'm stuck. This is what I have so far:
def main():
again = 'y'
while again == 'y':
pos_values = []
neg_values = []
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
elif value < 0:
neg_values.append(value)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
else:
print(sum.pos_values)
print(sum.neg_values)
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
total = 0
all_values = neg_values + pos_values
print[all_values]
print(total + pos_values)
print(total + neg_values)
main()
I'm just a first year student with no prior experience, so please be gentle!
Once you fix the logic error pointed out by Mike Scotty, the other problems are really just syntax errors. sum.pos_values will give you AttributeError: 'builtin_function_or_method' object has no attribute 'pos_values' (because sum is a built-in function and so needs () not .); and print[all_values] will give you a syntax error (because print is also a built-in function and so needs () not []). Your original code doesn't store zeroes in either list: I haven't changed that. And the output format is a guess on my part.
def main():
again = 'y'
pos_values = []
neg_values = []
while again == 'y':
value = int(input("Please enter value: "))
if value > 0:
pos_values.append(value)
elif value < 0:
neg_values.append(value)
else: #edit: terminate also on 0 input
break
print('Would you like to add another value?')
again = input('y = yes; n = no: ')
all_values = neg_values + pos_values
print(sum(all_values),all_values)
print(sum(pos_values),pos_values)
print(sum(neg_values),neg_values)
Currently I have my data in a directory
myDict = {'a':'Andy','b':'Bill','c':'Carly' }
I want to achieve something like
input = a --> output = Andy
input = ab --> output = Andy Bill
input = abc --> output = Andy Bill Carly
How can I do that ? Please help me
def girdi_al():
isim = input("isim giriniz: ")
return isim
def isim_donustur(isim):
cikti = isim()
donusum = {'a':'Ankara','b':'Bursa','c':'Ceyhan'}
string = ''
for char in cikti:
string += donusum[char] + ' '
print(string )
def main():
isim_donustur(girdi_al)
# === main ===
main()
Iterate through the individual letters of the input string.
Look up each item in the dictionary.
Concatenate the results as you go.
Can you handle each of those capabilities? If not, please post your best attempt and a description of the problem.
isim is not a function, and all you need to do is access that key in the dictionary
def girdi_al():
isim = input("isim giriniz: ")
return isim
def isim_donustur(isim):
cikti = isim
donusum = {'a':'Ankara','b':'Bursa','c':'Ceyhan'}
#How can I do?
result = []
for letter in cikti:
result.append(donusum[cikti])
print(' '.join(result))
def main():
isim_donustur(girdi_al)
# === main ===
main()
somthing like this
myDict = {'a':'Andy','b':'Bill','c':'Carly' }
input_str = "abc"
" ".join([v for k,v in myDict.items() if k in list(input_str)])
d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
ch = input("Enter your value: ")
How can I search inputted value from these dictionaries?
and if found value then it returns Found else return not found.
Why are a search value in different dictionary rather than in one??
Try this
merge all dictionary in one
d5 = {**d1, **d2, **d3, **d4}
and then check
if ch in d5 .values():
print "Found"
else:
print "Not Found"
Make a list of dictionaries and search in it:
d1 = {'name': 'Sagar','age': 25}
d2 = {'name': 'Sassdr', 'age':122}
d3 = {'name': 'Saga23weer', 'age':123344}
d4 = {'name': '2133Sagar', 'age':14322}
d = [d1,d2,d3,d4]
def check(ch):
for entry in d:
if entry["name"] == ch:
return("found")
return ("Not found")
while True:
ch = input("Enter your value: ")
if ch == "stop":
break
print(check(ch))
Output:
>>>
Enter your value: Sagar
found
Enter your value: Someone
Not found
Enter your value: 2133Sagar
found
Enter your value: stop
The effect you want is called key swap. This snippet is the implementation:
def keyswap(yourdict):
cache = {}
for i in yourdict.keys():
cache[yourdict[i]] = i
for i in cache.keys():
yourdict[i] = cache[i]
del cache
It keyswaps inplace.
You can use following code
Python2
def IsFound():
list_dict = [d1, d2, d3, d4]
values_list = []
for each in list_dict:
values_list += each.values()
ch = input('enter your value')
if ch in values_list:
return 'Found'
else:
return 'Not Found'
Python3
def IsFound():
dict = {**d1, **d2, **d3, **d4}
ch = input('enter your value')
if ch in dict.values():
return 'Found'
else:
return 'Not Found'
you need to do:
get the values of dict;
search all dicts;
mark result as "Found" if matches.
for step 1:
dict.values()
for step 2:
there's many way to combine all dicts, as everybody gives.
you can pick all values first to set a new list, then search if your input matches like this:
# combine all dicts
d = d1.values() + d2.values() +d3.values() + d4.values()
# judge if matches
if ch in d:
# do something
hope this code can release your confuse.