how to fill a dict with None for all keys (given in a list) in Python 3.3
(P)对于一个EDOCX1,字母名称0,字母名称1,我需要Fill a(Part of a)Dictionary to be Empty。I found no immediate solution for it.有人吗?(p)(P)Like with(p)字母名称(P)伪(p)字母名称(P)结果(p)字母名称(P)So that(p)字母名称(P)页:1(p)字母名称
对于内置的dict方法fromkeys,这是很自然的:
1 2 3 4 | >>> dict.fromkeys('abcd',None) {'a': None, 'c': None, 'b': None, 'd': None} >>> dict.fromkeys(['first','last'],None) {'last': None, 'first': None} |
完全不需要听写理解(2.7以上)或列表理解。
这可以通过简单的词典理解来实现:
1 | {key: None for key in keys} |
例如:
1 2 3 | >>> keys = ["first","last"] >>> {key: None for key in keys} {'last': None, 'first': None} |
号
编辑:似乎
1 2 3 4 | python -m timeit -s"keys = list(range(1000))""{key: None for key in keys}" 10000 loops, best of 3: 59.4 usec per loop python -m timeit -s"keys = list(range(1000))""dict.fromkeys(keys)" 10000 loops, best of 3: 32.1 usec per loop |
像这样?
1 2 3 4 5 | >>> fieldnames = ['first', 'last'] >>> row = dict((h, None) for h in fieldnames) >>> row {'last': None, 'first': None} >>> |
。