Search code examples
pythonlistdictionarylist-comprehensiondictionary-comprehension

create nested dictionary from list of lists


I want to create a nested dictionary from list of lists. Following is the list

  ls3 = [['YOU', 'HE', 'EST8'],
 ['YOU', 'HE', 'OLM6'],
 ['YOU', 'SLO', 'WLR8'],
 ['ARE', 'KLP', 'EST6'],
 ['ARE', 'POL', 'WLR4'],
 ['DOING', 'TIS', 'OIL8'],
 ['GREAT', 'POL', 'EOL6'],
 ['WORK', 'KOE', 'RIW8'],
 ['WORK', 'KOE', 'PNG4'],
 ['WORK', 'ROE', 'ERC8'],
 ['WORK', 'ROE', 'WQD6'],
 ['KEEP', 'PAR', 'KOM8'],
 ['KEEP', 'PAR', 'RTW6'],
 ['KEEP', 'PIL', 'XCE4'],
 ['KEEP', 'PIL', 'ACE8'],
 ['ROCKING', 'OUL', 'AZS6'],
 ['ROCKING', 'OUL', 'RVX8']]

below is my code and so far I was able to create this:

di = {}
di2 = {}
for i,j,k in ls3:
   di.setdefault(i, []).extend([j,k])
for i,j in di.items(): 
   di2.update({i:{j[0]:j[1:]}})

My output :

{'YOU': {'HE': ['EST8', 'HE', 'OLM6', 'SLO', 'WLR8']},
 'ARE': {'KLP': ['EST6', 'POL', 'WLR4']},
 'DOING': {'TIS': ['OIL8']},
 'GREAT': {'POL': ['EOL6']},
 'WORK': {'KOE': ['RIW8', 'KOE', 'PNG4', 'ROE', 'ERC8', 'ROE', 'WQD6']},
 'KEEP': {'PAR': ['KOM8', 'PAR', 'RTW6', 'PIL', 'XCE4', 'PIL', 'ACE8']},
 'ROCKING': {'OUL': ['AZS6', 'OUL', 'RVX8']}}

Expected output :

{{'YOU':{'HE':{'EST':8,'OLM':6},'SLO':{'WLR':8}}}, 
{'ARE':{'KLP':{'EST':6},'POL':{'WLR':4}}}, and so on}

Solution

  • The double setdefault is for the 2 nested dicts.

    The last part is for splitting the digit. If it's more than a single digit, you should use a regex.

    di = {}
    for i,j,k in ls3:
       di.setdefault(i, {}).setdefault(j, {})[k[:-1]] = int(k[-1])