python dict.fromkeys()返回空

slo*_*oow 2 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
Run Code Online (Sandbox Code Playgroud)

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

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

Jas*_*mbs 11

fromkeys是一种类方法,意思是

newusr.fromkeys(userlist, 0)
Run Code Online (Sandbox Code Playgroud)

和呼叫完全一样

dict.fromkeys(userlist, 0)
Run Code Online (Sandbox Code Playgroud)

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

newusr = dict.fromkeys(userlist, 0)
return newusr
Run Code Online (Sandbox Code Playgroud)