Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create nested dictionary one liner

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)}
like image 652
Dnaiel Avatar asked Aug 12 '26 06:08

Dnaiel


2 Answers

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}]}
}
like image 77
cs95 Avatar answered Aug 13 '26 21:08

cs95


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}}}
like image 27
Ajax1234 Avatar answered Aug 13 '26 21:08

Ajax1234