I am using map to pass input parameters from STDIN to my function, dict_add,but when I print out my dictionary, it is empty.
Can someone please tell me where I am going wrong?
Not doing this for any reason, just practicing python code.
store = {}
def dict_add(n):
store[n] = store.get(n,0) 1
results = map(dict_add,input("Number: ").split())
print(store) # comes out empty
CodePudding user response:
map
is an iterator, so dict_add
doesn't actually get called until you iterate it in some way. Example:
list(map(dict_add,input("Number: ").split()))
or
for _ in map(dict_add,input("Number: ").split()):
pass
I'm not saying this is the best way to achieve what you're trying to do, but it's why you're seeing this behaviour.
CodePudding user response:
I'm not sure why you use map
, you can just pass in the value.
also .split()
return an array and I think you want to pass the input as a value
also result variable is never used
store = {}
def dict_add(n):
global store
store[n] = store.get(n, 0) 1
dict_add(input("Number: "))
print(store) # {'1': 1}
you can do something like this in a loop, so it return a larger dict
store = {}
def dict_add(n):
global store
store[n] = store.get(n, 0) 1
for count in range(5):
dict_add(input("Number: "))
print(store) # {'1': 2, '2': 1, '3': 1, '4': 1}