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

These are my WanderingThoughts
(About the blog)

GettingAround
Full index of entries
Recent comments

This is part of CSpace, and is written by ChrisSiebenmann.

* * *

Atom feeds are available; see the bottom of most pages.

This is a DWiki.
(Help)

Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web

Search:
Written on 29 May 2006.
(Previous | Next)

Page tools: View Source, Add Comment.
Search:
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.