create nested dictionary one liner

廉价感情. 提交于 2021-02-07 20:12:22

问题


Hi I have three lists and I want to create a three-level nested dictionary using one line.

i.e.,

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}}

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)}

回答1:


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}}
}

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}]}
}



回答2:


You can also use recursion with a simpler loop:

l1 = ['a','b']
l2 = ['1', '2', '3']
l3 = ['d','e']
def combinations(d):
  return {i:combinations(d[1:]) if d[1:] else 0 for i in d[0]}

print(combinations([l1, l2, l3]))

Output:

{'b': {'1': {'d': 0, 'e': 0}, '2': {'d': 0, 'e': 0}, '3': {'d': 0, 'e': 0}}, 'a': {'1': {'d': 0, 'e': 0}, '2': {'d': 0, 'e': 0}, '3': {'d': 0, 'e': 0}}}

Edit: true one-liner:

print((lambda d:{i:combination(d[1:]) if d[1:] else 0 for i in d[0]})([l1, l2, l3]))

Output:

{'b': {'1': {'d': 0, 'e': 0}, '2': {'d': 0, 'e': 0}, '3': {'d': 0, 'e': 0}}, 'a': {'1': {'d': 0, 'e': 0}, '2': {'d': 0, 'e': 0}, '3': {'d': 0, 'e': 0}}}


来源:https://stackoverflow.com/questions/50279889/create-nested-dictionary-one-liner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!