我想从这里得到:
keys = [1,2,3]
:
{1: None, 2: None, 3: None}
有蟒式的方法吗?
这是一种丑陋的方式:
>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
我想从这里得到:
keys = [1,2,3]
:
{1: None, 2: None, 3: None}
有蟒式的方法吗?
这是一种丑陋的方式:
>>> keys = [1,2,3]
>>> dict([(1,2)])
{1: 2}
>>> dict(zip(keys, [None]*len(keys)))
{1: None, 2: None, 3: None}
当前回答
列表推导式可用于构建键-值对列表,然后将其传递给dict构造函数。因此:
>>> keys = {"a", "b", "c", "d"}
>>> d = dict([(key, []) for key in keys])
>>> d
{'d': [], 'c': [], 'a': [], 'b': []}
值表达式每次都被求值,在上面的例子中创建单独的列表:
>>> d['a'].append('test')
>>> d
{'d': [], 'c': [], 'a': ['test'], 'b': []}
其他回答
在许多想要为任意键附加默认/初始值的工作流中,不需要提前逐个散列每个键。您可以使用collections.defaultdict。例如:
from collections import defaultdict
d = defaultdict(lambda: None)
print(d[1]) # None
print(d[2]) # None
print(d[3]) # None
这是更有效的,它节省了在实例化时对所有键进行哈希。此外,defaultdict是dict的一个子类,所以通常不需要转换回常规字典。
对于需要对允许的键进行控制的工作流,您可以根据接受的答案使用dict.fromkeys:
d = dict.fromkeys([1, 2, 3, 4])
简单地迭代并将值添加到空字典:
d = {}
for i in keys:
d[i] = None
只是因为dict构造函数与zip很好地工作很有趣,你可以重复默认值并将其压缩到键:
from itertools import repeat
keys = [1, 2, 3]
default_value = None
d = dict(zip(keys, repeat(default_value)))
print(d)
将:
{1: None, 2: None, 3: None}
Repeat为传递给它的元素创建了一个无限迭代器,但由于zip停止在最短的可迭代对象上,所有工作正常。
Dict.fromkeys直接解决了问题:
>>> dict.fromkeys([1, 2, 3, 4])
{1: None, 2: None, 3: None, 4: None}
这实际上是一个类方法,所以它也适用于dict-子类(如collections.defaultdict)。
可选的第二个参数,默认为None,指定用于键的值。注意,相同的对象将用于每个键,这可能会导致可变值的问题:
>>> x = dict.fromkeys([1, 2, 3, 4], [])
>>> x[1].append('test')
>>> x
{1: ['test'], 2: ['test'], 3: ['test'], 4: ['test']}
如果这是不可接受的,请参阅如何初始化值为不同空列表的字典?为了解决问题。
列表推导式可用于构建键-值对列表,然后将其传递给dict构造函数。因此:
>>> keys = {"a", "b", "c", "d"}
>>> d = dict([(key, []) for key in keys])
>>> d
{'d': [], 'c': [], 'a': [], 'b': []}
值表达式每次都被求值,在上面的例子中创建单独的列表:
>>> d['a'].append('test')
>>> d
{'d': [], 'c': [], 'a': ['test'], 'b': []}