我想从中得到:
keys = [1,2,3]
到这里:
{1: None, 2: None, 3: None}
有pythonic的方法吗?
这是一种丑陋的做法:
>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
最佳答案
dict.fromkeys
直接解决问题:
>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}
这实际上是一个类方法,因此它也适用于字典子类(如 collections.defaultdict
)。
可选的第二个参数,默认为 None
,指定用于键的值。请注意,相同的对象将用于每个键,这可能会导致可变值出现问题:
>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}
https://stackoverflow.com/questions/2241891/