[英]Using list comprehension to create nested dictionary with empty lists
I want to create a dictionary with dictionaries with empty lists inside.我想创建一个字典,里面有空列表的字典。 The nested dictionaries all have the same keys.
嵌套字典都具有相同的键。 I have a solution already;
我已经有了解决方案; but I really don't think it is smart:
但我真的不认为这很聪明:
outer_keys = ['out_a', 'out_b', 'out_c']
inner_keys = ['in_a', 'in_b', 'in_c']
dictionary = {}
for o in outer_keys:
dictionary[o] = {}
for i in inner_keys:
dictionary[o][i] = list()
This one works.这个有效。 The result is:
结果是:
{'out_a':
{'in_a': [],
'in_b': [],
'in_c': []},
{'out_b':
{'in_a': [],
'in_b': [],
'in_c': []},
{'out_c':
{'in_a': [],
'in_b': [],
'in_c': []}}
But is there a way to do it in a single line?但是有没有办法在一行中做到这一点?
I tried我试过了
dictionary = dict([(o, {i: list()}) for o in outer_keys for i in inner_keys])
which unfortunately only saves the last inner_key and leads to:不幸的是,它只保存了最后一个 inner_key 并导致:
{'out_a':
{'in_c': []},
'out_b':
{'in_c': []},
'out_c':
{'in_c': []}}
You can used a nested dict comprehension - the outer comprehension creates the dictionary, and for each key in it, another inner comprehension creates the inner dictionary您可以使用嵌套的字典理解 - 外部理解创建字典,并且对于其中的每个键,另一个内部理解创建内部字典
dictionary = {o: {i:list() for i in inner_keys} for o in outer_keys}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.