Wandering Thoughts archives

2006-05-29

An obvious way to do bulk initialization of dictionaries

Every so often in my Python programs I need to initialize a dictionary with a whole bunch of values (and then pass it off somewhere). For a long time, my usual approach to this was:

d = {}
d['a'] = b.what
d['c'] = foo(d)
....

Recently I stumbled over the better way to do this, which is embarrassingly obvious in retrospect:

d = {
      'a': b.what,
      'c': foo(d),
      'e': bar(f, 28),
      ....
      }

As my example shows, the initial values can of course be any expression, not just simple values (which has been one of the reasons I tended to wind up writing the 'd['a'] = b.what' form). And with conditional expressions (either the current 'A and B or C' hack or the real version that will show up in Python 2.5), you can go even further in what can be swallowed into a one-liner initializer.

Of course, you can also use this to add several things to an existing dictionary:

d.update({
           'a': (b1, b2),
           'c': foo(d),
           ...
           })

(Although at this point I start thinking about creating a temporary dictionary to stuff all the values in and then doing 'd.update(tempd)', because otherwise the code looks a bit peculiar to me.)

It's humbling to keep discovering Python idioms like this, even after years of off and on programming in Python. Since I often discover them by reading other people's code, I probably should make more of an effort to seek out and read good Python code.

(I believe I stumbled over this idiom in someone's WSGI server code.)

python/BulkDictionaryInitialization written at 00:43:10; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.