How to initialize a dict with keys from a list and empty value in Python?
我想从中得到:
1 | keys = [1,2,3] |
对此:
1 | {1: None, 2: None, 3: None} |
有没有一种Python式的方法?
这是一种丑陋的方式:
1 2 3 4 5 | >>> keys = [1,2,3] >>> dict([(1,2)]) {1: 2} >>> dict(zip(keys, [None]*len(keys))) {1: None, 2: None, 3: None} |
这实际上是一个类方法,因此它也适用于dict子类(如
没人愿意给出听写理解的解决方案?
1 2 3 | >>> 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} |
1 | dict.fromkeys(keys, None) |
1 2 3 | >>> keyDict = {"a","b","c","d"} >>> dict([(key, []) for key in keyDict]) |
输出:
1 | {'a': [], 'c': [], 'b': [], 'd': []} |
1 2 3 | d = {} for i in keys: d[i] = None |
在许多要为任意键附加默认值/初始值的工作流中,不需要提前单独散列每个键。您可以使用
1 2 3 4 5 6 7 | from collections import defaultdict d = defaultdict(lambda: None) print(d[1]) # None print(d[2]) # None print(d[3]) # None |
这更有效,它省去了在实例化时必须散列所有键的麻烦。此外,
对于需要对允许键进行控制的工作流,可以根据接受的答案使用
1 | d = dict.fromkeys([1, 2, 3, 4]) |