To declare an empty dictionary, I do:
mydict = dict()
To declare an empty dictionary of empty dictionaries, I can do also:
mydictofdict = dict()
Then add dictionaries when needed:
mydict1 = dict()
mydictofdict.update({1:mydict1})
and elements in them when desired:
mydictofdict[1].update({'mykey1':'myval1'})
Is it pythonic? Is there a better way to perform it?
You can use collections.defaultdict for a nested dictionary, where you define an initial value of a dictionary
from collections import defaultdict
#Use the initial value as a dictionary
dct = defaultdict(dict)
dct['a']['b'] = 'c'
dct['d']['e'] = 'f'
print(dct)
The output will be
defaultdict(<class 'dict'>, {'a': {'b': 'c'}, 'd': {'e': 'f'}})
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