Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I correct my code to produce a nested dictionary?

I am trying to create a nested dictionary. I have a list of tuples (called 'kinetic_parameters') which looks like this:

('New Model','v7','k1',0.1)
('New Model','v8','k2',0.2)
('New Model','v8','k3',0.3)

I need the second column to be the outer key and the value to be another dictionary with inner key being the third column and value being the number in the fourth.

I currently have:

    for i in kinetic_parameters:
        dict[i[1]]={}
        dict[i[1]][i[2]]=i[3]

But this code will not deal with multiple keys in the inner dictionary so I lose some information. Does anybody know how to correct my problem?

I'm using Python 2.7 and I want the output to look like this:

{'v7': {'k1': 0.1}, 'v8':{'k2':0.2, 'k3': 0.3}}
like image 434
CiaranWelsh Avatar asked Jan 08 '23 02:01

CiaranWelsh


2 Answers

Use a defaultdict, and don't use dict as a variable name, since we need it to refer to the dictionary type:

import collections
d = collections.defaultdict(dict)
for i in kinetic_parameters:
    d[i[1]][i[2]]=i[3]

This will create the dictionaries automatically.

like image 59
Kevin Avatar answered Jan 10 '23 17:01

Kevin


Right, if the major ("outer") key has been seen before you should be using the existing dictionary. Or put the other way around: Create an embedded dictionary only if does not exist, then add the value. Here's the logic, using tuple assignment for clarity:

nested = dict()
for row in kinetic_parameters:
    _model, outkey, inkey, val = row
    if outkey not in d:
        nested[outkey] = dict()  
    nested[outkey][inkey] = val

Or you can skip the existence check by using defaultdict, which can create new embedded dicts as needed:

from collections import defaultdict
nested = defaultdict(dict)
for row in kinetic_parameters:
    _model, outkey, inkey, val = row
    nested[outkey][inkey] = val
like image 24
alexis Avatar answered Jan 10 '23 15:01

alexis