从可迭代对象创建字典
创建一个字典并给它一些默认值,最简单的方法是什么呢?我试过:
>>> x = dict(zip(range(0, 10), range(0)))
但是这不行,因为我以为的 range(0) 其实并不是一个可迭代的东西(不过我还是试了!)
那我该怎么做呢?如果我这样做:
>>> x = dict(zip(range(0, 10), 0))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: zip argument #2 must support iteration
这也不行。有什么建议吗?
4 个回答
2
PulpFiction提供了一种实用的方法来实现这个功能。不过,出于兴趣,你也可以通过使用itertools.repeat
来让你的解决方案实现重复的0。
x = dict(zip(range(0, 10), itertools.repeat(0)))
35
在Python 3中,你可以使用字典推导式来快速创建字典。
>>> {i:0 for i in range(0,10)}
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}
幸运的是,这个功能在Python 2.7中也可以使用,所以你在那儿也能找到它。
25
你需要用到 dict.fromkeys
这个方法,它正好能满足你的需求。
根据文档的说明:
fromkeys(...)
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v.
v defaults to None.
所以你需要的是:
>>> x = dict.fromkeys(range(0, 10), 0)
>>> x
{0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0}