Different implemention of nested dict in Python

· Read in about 1 min · (177 Words)

Different implemention of nested dict in Python.

Code is also available on gist

#!/usr/bin/env python
# different implemention of nested dict in Python
from collections import defaultdict


# from: http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python
class AutoVivification(dict):
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value


# from: http://stackoverflow.com/questions/635483/what-is-the-best-way-to-implement-nested-dictionaries-in-python
class Vividict(dict):
    def __missing__(self, key):
        value = self[key] = type(self)()
        return value


# from: http://stackoverflow.com/questions/651794/whats-the-best-way-to-initialize-a-dict-of-dicts-in-python
def ddict():
    return defaultdict(ddict)


# from @lpp1985 https://github.com/lpp1985
class Ddict(defaultdict, dict):
    def __init__(self):
        defaultdict.__init__(self, Ddict)

    def __repr__(self):
        return dict.__repr__(self)

# test
for c in [AutoVivification, Vividict, ddict, Ddict]:
    print("\n%s\n%s" % ('=' * 78, c))

    d = c()
    d[1][2][3] = 4
    d['a']['b']['c'] = 'd'

    print(d)

ResultHUGOMORE42

==============================================================================
<class '__main__.AutoVivification'>
{'a': {'b': {'c': 'd'}}, 1: {2: {3: 4}}}

==============================================================================
<class '__main__.Vividict'>
{'a': {'b': {'c': 'd'}}, 1: {2: {3: 4}}}

==============================================================================
<function ddict at 0x7f8c02cabf50>
defaultdict(<function ddict at 0x7f8c02cabf50>, {'a': defaultdict(<function ddict at 0x7f8c02cabf50>, {'b': defaultdict(<function ddict at 0x7f8c02cabf50>, {'c': 'd'})}), 1: defaultdict(<function ddict at 0x7f8c02cabf50>, {2: defaultdict(<function ddict at 0x7f8c02cabf50>, {3: 4})})})

==============================================================================
<class '__main__.Ddict'>
{'a': {'b': {'c': 'd'}}, 1: {2: {3: 4}}}