Python Multi-dimensional dicts using defaultdict

I asked previously how to avoid code like this:

# Implement d[3][4] = 5
if not 3 in d:
  d[3] = {}
d[3][4] = 5

I found the answer, and it lies in collections.defaultdict. defaultdict is just like dict, except that you pre-specify an initial default values for items that aren’t present. For example:

d = defaultdict(lambda: 1)
d[5] += 3
print d

Will print out “{5: 4}” and I didn’t have to explicitly assign d[5] to 1 before doing the increment.

This leads to the question: Can you create a defaultdict whose default is another defaultdict? Yes!

d = defaultdict(defaultdict)
d[3][4] = 5

Is totally valid. But, that inner defaultdict doesn’t have a good default value, so if you want more dimensions, you have to start stacking them up, like this:

d = defaultdict(lambda: defaultdict(defaultdict))
d[3][4][5] = 6

And so on, as you want more dimensions. Not a huge price to pay, I guess.

This entry was posted in General and tagged , , . Bookmark the permalink.

3 Responses to Python Multi-dimensional dicts using defaultdict

  1. Brian Beach says:

    If you want arbitrarily and unevenly deep dictionaries, you can define a recursive defaultdict like this:

    from collections import defaultdict

    def deepDefaultDict():
    return defaultdict(deepDefaultDict)

    d = deepDefaultDict()
    d[1] = “foo”
    d[2][3][4][5] = “bar”
    print d

  2. Pingback: [todo austin] » Blog Archive » python multi-dimensional dictionary

  3. stephen says:

    You can’t recursively call the dictionary but the link below contains a nice explanation.

    http://stackoverflow.com/questions/2388302/best-way-to-define-multidimensional-dictionaries-in-python

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>