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

Viewed 4411

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?

2 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'}})

You can create empty dict with {}:

d = {}

You can create dict of dict (as values) the way like the first:

d = {
    1: {},
    2: {}
}

You can modify the dict's value by []:

d = {1: 0}
d[1] = 1
d

{1: 1}

The similar with dict in dict:

d = {
    1: {},
    2: {}
}
d[1][4] = 5
d

{1: {4: 5}, 2: {}}

If you want to create a dict of dicts according to the list of keys, you can use dict comprehensions:

keys = [1,2,3,4,5]
d = {key: {} for key in keys}
d

{1: {}, 2: {}, 3: {}, 4: {}, 5: {}}

Related