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}}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With