Dictionary comprehension

Magnus Lie Hetland mlh at idi.ntnu.no
Thu Jun 7 14:14:00 EDT 2001


It seems to me that dictionary comprehension (in exactly
the same style as list comprehension [1], and as proposed
for set comprehension [2]) might be useful, and I wondered
if anyone else agreed (and perhaps if work had already
been done on this, or if it has already been discussed
somewhere...)

While list comprehension works like this

  [expr for var1 in seq1 for var2 in seq2 ... if bool]

set comprehension will (if approved) work in the same manner,
except with curly braces:

  {expr for var1 in seq1 for var2 in seq2 ... if bool}

My suggestion for dictionary comprehension syntax is (IMO)
obvious:

  {expr1:expr2 for var1 in seq1 for var2 in seq2 ... if bool}

where expr1 is the key corresponding to expr2. Duplicate
keys will overwrite earlier ones, the order being uniquely
determined by the generator part (for var in seq ...).

Any thoughts? Should a PEP be written, or is this just an
Evil(tm) idea? If nothing else, it would give a simple
solution to the frequently asked question "how to I invert
a dictionary (with unique values)?":

  inverted = {dict[key]:key for key in dict}

or possibly faster (I don't really know):

  inverted = {val:key for key, val in dict.iteritems()}

(assuming that the new dictionary iteration syntax will
make its way into 2.2...)

[1] http://python.sourceforge.net/peps/pep-0202.html
[2] http://python.sourceforge.net/peps/pep-0218.html

--

  Magnus Lie Hetland         http://www.hetland.org

 "Reality is that which, when you stop believing in
  it, doesn't go away."           -- Philip K. Dick






More information about the Python-list mailing list