Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare an empty dictionary of empty dictionaries in Python 2.7?

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?

like image 988
lalebarde Avatar asked Jan 27 '23 05:01

lalebarde


1 Answers

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'}})
like image 95
Devesh Kumar Singh Avatar answered Jan 30 '23 01:01

Devesh Kumar Singh