创建嵌套字典一班轮 [英] create nested dictionary one liner
问题描述
我有三个列表,我想用一行创建一个三级嵌套字典.
Hi I have three lists and I want to create a three-level nested dictionary using one line.
即
l1 = ['a','b']
l2 = ['1', '2', '3']
l3 = ['d','e']
我想创建以下嵌套词典:
I'd want to create the following nested dictionary:
nd = {'a':{'1':{'d':0},{'e':0},'2':{'d':0},{'e':0},'3':{'d':0},{'e':0},'b':'a':{'1':{'d':0},{'e':0},'2':{'d':0},{'e':0},'3':{'d':0},{'e':0}}
我尝试使用zip进行外部循环并添加列表,但是元素被替换了.即,这不起作用:
I tried using zip to do the outer loop and add the lists but elements get replaced. I.e., this does not work:
nd = {i:{j:{k:[]}} for i in zip(l1,l2,l3)}
推荐答案
zip
在这里不起作用. zip
连续遍历所有3个列表.您需要的是产品-有效地是3个嵌套循环.您可以以一些可读性为代价,将其扩展为单个字典理解.
zip
will not do here. zip
iterates over all 3 lists consecutively. What you need are products—effectively 3 nested loops. You can flatten this into a single dictionary comprehension at the cost of some readability.
>>> {i : {j : {k : 0 for k in l3} for j in l2} for i in l1}
{'a': {'1': {'d': 0, 'e': 0},
'2': {'d': 0, 'e': 0},
'3': {'d': 0, 'e': 0}},
'b': {'1': {'d': 0, 'e': 0},
'2': {'d': 0, 'e': 0},
'3': {'d': 0, 'e': 0}}
}
或者,如果您想要最底层的单键词典列表(如您的o/p所建议),
Or, if you want a list of single-key dictionaries at the bottom-most level (as your o/p suggests),
>>> {i : {j : [{k : 0} for k in l3] for j in l2} for i in l1}
{'a': {'1': [{'d': 0}, {'e': 0}],
'2': [{'d': 0}, {'e': 0}],
'3': [{'d': 0}, {'e': 0}]},
'b': {'1': [{'d': 0}, {'e': 0}],
'2': [{'d': 0}, {'e': 0}],
'3': [{'d': 0}, {'e': 0}]}
}
这篇关于创建嵌套字典一班轮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!