Alex Rivera | Logout

Generating dictionary keys on the fly

Asked 2010-08-04T11:34:23.243
13

Working with deeply nested python dicts, I would like to be able to assign values in such a data structure like this:

  mydict[key][subkey][subkey2]="value"

without having to check that mydict[key] etc. are actually set to be a dict, e.g. using

  if not key in mydict: mydict[key]={}

The creation of subdictionaries should happen on the fly. What is the most elegant way to allow something equivalent - maybe using decorators on the standard <type 'dict'>?

Edit
Report

1 Answer

4

I like Dave's answer better, but here's an alternative.

from collections import defaultdict
d = defaultdict(lambda : defaultdict(int))
>>> d['a']['b'] += 1
>>> d
defaultdict(<function <lambda> at 0x652f0>, {'a': defaultdict(<type 'int'>, {'b': 1})})
>>> d['a']['b']
1

http://tumble.philadams.net/post/85269428/python-nested-defaultdicts

It's definitely not pretty to have to use lambdas to implements the inner defaulted collections, but apparently necessary.

answered 2010-08-04T11:44:11.587

Your Answer