2

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.

slooow
  • 329
  • 1
  • 3
  • 10
  • 1
    If you like an answer, be sure to mark it as the accepted answer. It gives the responder reputation points and lets everyone else know you aren't looking for a better answer. – Jeffrey Harris Apr 01 '10 at 01:29

3 Answers3

10

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
  • 41,115
  • 10
  • 83
  • 93
3

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
  • 854,459
  • 170
  • 1,222
  • 1,395
2

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
  • 795,719
  • 175
  • 1,089
  • 1,143