What's the best way to initialize a dict of dicts in Python? [duplicate] What's the best way to initialize a dict of dicts in Python? [duplicate] python python

What's the best way to initialize a dict of dicts in Python? [duplicate]


If the amount of nesting you need is fixed, collections.defaultdict is wonderful.

e.g. nesting two deep:

myhash = collections.defaultdict(dict)myhash[1][2] = 3myhash[1][3] = 13myhash[2][4] = 9

If you want to go another level of nesting, you'll need to do something like:

myhash = collections.defaultdict(lambda : collections.defaultdict(dict))myhash[1][2][3] = 4myhash[1][3][3] = 5myhash[1][2]['test'] = 6

edit: MizardX points out that we can get full genericity with a simple function:

import collectionsdef makehash():    return collections.defaultdict(makehash)

Now we can do:

myhash = makehash()myhash[1][2] = 4myhash[1][3] = 8myhash[2][5][8] = 17# etc


class AutoVivification(dict):    """Implementation of perl's autovivification feature."""    def __getitem__(self, item):        try:            return dict.__getitem__(self, item)        except KeyError:            value = self[item] = type(self)()            return value

Testing:

a = AutoVivification()a[1][2][3] = 4a[1][3][3] = 5a[1][2]['test'] = 6print a

Output:

{1: {2: {'test': 6, 3: 4}, 3: {3: 5}}}


Is there a reason it needs to be a dict of dicts? If there's no compelling reason for that particular structure, you could simply index the dict with a tuple:

mydict = {('foo', 'bar', 'baz'):1} # Initializes dict with a key/value pairmydict[('foo', 'bar', 'baz')]      # Returns 1mydict[('foo', 'unbar')] = 2       # Sets a value for a new key

The parentheses are required if you initialize the dict with a tuple key, but you can omit them when setting/getting values using []:

mydict = {}                        # Initialized the dictmydict['foo', 'bar', 'baz'] = 1    # Sets a valuemydict['foo', 'bar', 'baz']        # Returns 1