An obvious way to do bulk initialization of dictionariesEvery 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:
Recently I stumbled over the better way to do this, which is embarrassingly obvious in retrospect:
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 ' Of course, you can also use this to add several things to an existing dictionary:
(Although at this point I start thinking about creating a
temporary dictionary to stuff all the values in and then
doing ' 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 GettingAround This is part of CSpace, and is written by ChrisSiebenmann. * * * Atom feeds are available; see the bottom of most pages. Categories: links, linux, programming, python, snark, solaris, spam, sysadmin, tech, unix, web |