开发者

python dict.fromkeys() returns empty

开发者 https://www.devze.com 2022-12-25 21:02 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消