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.
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.
You have to create each empty dict for each key like
Data = {}
Data['day1'] = {}
Data['day1']['e1'] = 4
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