An obvious way to do bulk initialization of dictionaries

May 29, 2006

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:

           '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.)

Written on 29 May 2006.
« Weekly spam summary on May 27th, 2006
An shell script idiom for choosing what file to operate on »

Page tools: View Source, Add Comment.
Login: Password:
Atom Syndication: Recent Comments.

Last modified: Mon May 29 00:43:10 2006
This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.