Nested dictionaries in Python

On August 12, 2010, in development, python, by Eugene

This isn’t exactly ground-breaking, but rather just a handy tip. If you’re looking to create nested dictionaries in Python, like a “multi-dimensional hash,” or just a “dict of dicts,” there is a very simple method. All you need to do is use the defaultdict class in the collections module. Defaultdict objects can specify what factory (method) to use when creating new elements in the dictionary. If you pass in “dict” as the argument, all members of your dictionary will themselves be dictionaries. Of course, you could pass in another type, such as list. For example, this will make a two-level dictionary:

>>> from collections import defaultdict
>>> double_dict = defaultdict(dict)
>>> double_dict['foo']['bar'] = 42
>>> double_dict['fun']['ball'] = 77
>>> double_dict['fun']
{'ball': 77}

What if you want an unlimited number of dicts within a dict? Well, all you need is a simple function to create a defaultdict(dict) object on the fly, like this:

>>> def make_infinite_dict():
 return defaultdict(make_infinite_dict)

>>> inf_dict = make_infinite_dict()
>>> inf_dict[1][2][3][4][5] = 100
>>> inf_dict[1][2][3][4][5]
100

Like I said, nothing magical, but it could come in handy

Check out my other Python-related posts!

 

Comments are closed.