views:

164

answers:

3

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.

+2  A: 

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!-)

Alex Martelli
+7  A: 

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
Jason R. Coombs
Thanks, that was really quick. Classes and instantiation seem still a bit alien for me.
slooow
@slooow: You should accept this answer if it helped you (tick the green check mark beside the question).
Felix Kling
+1  A: 

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.

Felix Kling