python dict.fromkeys() returns empty
I wrote the following function. It returns an empty dictionary when it should not. The code works on the command line without function. However I cannot see what is wrong with the function, so I have to appeal to your collective intelligence.
def enter_users_into_dict(userlist):
newusr = {}
newusr.fromkeys(userlist, 0)
return newusr
ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd
开发者_如何学编程It returns an empty dict {} where I would expect {'john': 0, 'mabel': 0}.
It is probably very simply but I don't see the solution.
fromkeys is a class method, meaning
newusr.fromkeys(userlist, 0)
is exactly the same as calling
dict.fromkeys(userlist, 0)
Both which return a dictionary of the keys in userlist. You need to assign it to something. Try this instead.
newusr = dict.fromkeys(userlist, 0)
return newusr
You need to collapse the function's body to
def enter_users_into_dict(userlist):
return dict.fromkeys(userlist, 0)
fromkeys
is a class method, thus doesn't affect any instance it may be called on (it's best to call it on the class -- that's clearer!), rather it returns the new dictionary it builds... and that's exactly the very dictionary you want to return, to!-)
It should be:
def enter_users_into_dict(userlist):
return dict.fromkeys(userlist, 0)
From the documentation:
fromkeys()
is a class method that returns a new dictionary.
精彩评论