dict comprehension is a proposed addition to the Python interpreter. In PEP 274, it is proposed to introduce a syntax on the lines of list comprehension, which produces a dictionary by looping over an iterator and evaluating expressions for key and value.

There's really only one reasonable way to do this (honestly, I came up with the exact same idea and syntax independently, then found it had been suggested already). Take list comprehension syntax, and mix in the way dictionary literals are expressed. You get

{i : chr(65+i) for i in range(4)}

which does exactly

dict([(i, chr(65+i)) for i in range(4)])

In other words, {k(i) : v(i) for i in some_iterator} will return a dictionary with an item for every i that some_iterator generates; the key will be the value of the expression k(i), and the value will be v(i). As with lists, there will be an optional if condition(i) extension, to filter only certain cases.

Possibly, you will also be able to (optionally) omit the key expression, in which case the implication is {i : v(i) for ...} (the "index" becomes the key).

This will be very cool.

Log in or register to write something here or to contact authors.