python dict.fromkeys()返回空

时间:2010-03-31 23:27:10

标签: python dictionary fromkeys

我写了以下功能。它不应该返回一个空字典。代码在没有功能的命令行上工作。但是我看不出这个功能有什么问题,所以我必须诉诸你的集体智慧。

def enter_users_into_dict(userlist):
    newusr = {}
    newusr.fromkeys(userlist, 0)
    return newusr

ul = ['john', 'mabel']
nd = enter_users_into_dict(ul)
print nd

它会返回一个空的dict {},我希望{'john':0,'mabel':0}。

可能非常简单,但我没有看到解决方案。

3 个答案:

答案 0 :(得分:11)

fromkeys是一种类方法,意思是

newusr.fromkeys(userlist, 0)

与调用

完全相同
dict.fromkeys(userlist, 0)

两者返回用户列表中键的字典。你需要将它分配给某些东西。试试这个。

newusr = dict.fromkeys(userlist, 0)
return newusr

答案 1 :(得分:3)

您需要将函数的主体折叠为

def enter_users_into_dict(userlist):
    return dict.fromkeys(userlist, 0)

fromkeys是一个类方法,因此不会影响它可能被调用的任何实例(最好在类上调用它 - 这更清楚!),而不是返回它建立的新词典......这就是你想要返回的词典! - )

答案 2 :(得分:2)

应该是:

def enter_users_into_dict(userlist):
    return dict.fromkeys(userlist, 0)

来自documentation

  

fromkeys()类方法返回新词典。

相关问题