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.

Tagged , ,

3 thoughts on “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. [...] Ref: http://slacy.com/blog/2010/05/python-multi-dimensional-dicts-using-defaultdict/ 六月 16th, 2011 in coding note | tags: python blog comments powered by Disqus /* [...]

  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