Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign Nested Keys and Values in Dictionaries

I need to assign nested values to a dictionary. I have simplified my question for ease of understanding:

Data = {}   
day1 = 'March12'
day2 = 'March14'
e1 = 'experiment1'
e2 = 'experiment2'

Data[day1][e1] = 4 

But the Data[day1][e1] = 4 command does not function (for the same reason as test = {} ; test["foo"]["bar"] = 0). Is there a workaround to do this?

I tried to do things like:

me1 = {e1 : 4}
me2 = {e2 : 5}
Data = {day1 : me1}
Data = {day2 : me2}

But I couldn't succeed; all the things I wrote have somehow overwritten the existing values or were not as I would like to have. I'm probably missing out something...

Some additional notes: At the begininng don't have any info about the length of the dictionary, or how it exactly looks like. And instead of the value 4, I assign an object as a value. I need to use such a structure (Data[day1][e1]) because I have to assign the objects to their keys inside a loop.

like image 648
T-800 Avatar asked Mar 17 '14 13:03

T-800


2 Answers

You need to store a new dictionary inside of Data to make this work:

Data[day1] = {}
Data[day1][e1] = 4

but normally you'd first test to see if that dictionary is there yet; using dict.setdefault() to make that a one-step process:

if day1 not in Data
    Data[day1] = {}
Data[day1][e1] = 4

The collections.defaultdict() type automates that process:

from collections import defaultdict

Data = defaultdict(dict)
Data[day1][e1] = 4

The day1 key doesn't exist yet, but the defaultdict() object then calls the configured constructor (dict here) to produce a new value for that key as needed.

like image 149
Martijn Pieters Avatar answered Oct 23 '22 23:10

Martijn Pieters


You have to create each empty dict for each key like

Data = {}

Data['day1'] = {}

Data['day1']['e1'] = 4

like image 26
Nilesh Avatar answered Oct 23 '22 21:10

Nilesh