如何用列表中的键和Python中的空值初始化字典?
我想从这里得到:
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([1, 2, 3, 4])
这实际上是一个classmethod,所以它也适用于dict-subclasses(比如collections.defaultdict
)。 可选的第二个参数指定用于键的值(默认为None
。
没有人关心提供一个字典的理解解决scheme?
>>> keys = [1,2,3,5,6,7] >>> {key: None for key in keys} {1: None, 2: None, 3: None, 5: None, 6: None, 7: None}
dict.fromkeys(keys, None)
>>> keyDict = {"a","b","c","d"} >>> dict([(key, []) for key in keyDict])
输出:
{'a': [], 'c': [], 'b': [], 'd': []}
d = {} for i in keys: d[i] = None
d = {} for i in range(len(keys)): d.update({i+1:[]})