我有这个:
set_of_strings = {'abc', 'def', 'xyz'}
我想创建这个:
dict_of_dicts = {
'abc': {'pr': 0, 'wt': 0},
'def' : {'pr': 0, 'wt': 0},
'xyz' : {'pr': 0, 'wt': 0}
}
什么是pythonic方式?(Python 2.7)
我有这个:
set_of_strings = {'abc', 'def', 'xyz'}
我想创建这个:
dict_of_dicts = {
'abc': {'pr': 0, 'wt': 0},
'def' : {'pr': 0, 'wt': 0},
'xyz' : {'pr': 0, 'wt': 0}
}
什么是pythonic方式?(Python 2.7)
像这样?
>>> set_of_strings = {'abc', 'def', 'xyz'}
>>> dict_of_dicts = {}
>>> for key in set_of_strings:
... dict_of_dicts[key] = {'pr':0, 'wt':0}
...
>>> print dict_of_dicts
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}
作为字典理解:
>>> {k:{'pr':0, 'wt':0} for k in {'abc', 'def', 'xyz'}}
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}
或者,您可以执行以下操作:
>>> set_of_strings = {'abc', 'def', 'xyz'}
>>> value = {'pr': 0, 'wt': 0}
>>> dict(zip(set_of_strings, [value]*len(set_of_strings)))
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}
您还可以使用dict.fromkeys
:
>>> d = dict.fromkeys({'abc', 'def', 'xyz'}, {'pr': 0, 'wt': 0})
>>> d
{'xyz': {'pr': 0, 'wt': 0}, 'abc': {'pr': 0, 'wt': 0}, 'def': {'pr': 0, 'wt': 0}}
注意:
指定的值 ( {'pr': 0, 'wt': 0}
) 由所有键共享。
>>> d['xyz']['py'] = 1
>>> d
{'xyz': {'pr': 0, 'py': 1, 'wt': 0}, 'abc': {'pr': 0, 'py': 1, 'wt': 0}, 'def': {'pr': 0, 'py': 1, 'wt': 0}}
正如其他答案所示,有几种方法可以实现这一点,但 IMO 最(唯一?)pythonic 方式是使用 dict 理解:
keys = ...
{ k: { 'pr': 0, 'wt': 0 } for k in keys }
如果这些值是不可变的,那dict.fromkeys
很好,并且可能比 dict 理解更快。