Next / Previous / Contents / TCC Help System / NM Tech homepage

16.2. Dictionary comprehensions

New in Python 2.7 are dictionary comprehensions: a construct that allows you to build a dictionary dynamically, somewhat like Section 11.2, “List comprehensions”. Here is the general form:

{ ek: ev
  for v1 in s1
  for v2 in s2
  if c }

As with list comprehensions, you provide one or more for clauses and an optional if clause. For all possible combinations of the values in the for clauses that have a true value for the if clause, two expressions ek and ev are evaluated, and a new dictionary entry is added with key ek and value ev.

Here is an example. The Wikipedia article on the game of Scrabble gives the Scrabble score for each letter of the alphabet.

What we would like is a dictionary whose keys are letters, and each related value is the score. However, the Wikipedia article shows the score values grouped by score: the 1's together, the 2's together, and so on. So, to make it easy to check that we have entered the right score values and letters, we can use a list of tuples, where the first element of each tuple is the score and the second element is a string of all the letters with that score. We can then convert that list to the desired dictionary using a dictionary comprehension.

>>> scrabbleTuples = [ (1, "EAOINRTLSU"), (2, "DG"), (3, "BCMP"),
...                    (4, "FHVWY"), (5, "K"), (8, "JX"), (10, "QZ")]
>>> scrabbleMap = { letter: score
...                 for score, letterList in scrabbleTuples
...                 for letter in letterList }
>>> scrabbleMap['A']
>>> scrabbleMap['Z']

Evaluating the set comprehension proceeds as follows.

  1. In the first for clause, the first tuple is unpacked, setting score to 1 and letterList to "EAOINRTLSU".

  2. In the second for clause, letter is set to "E".

  3. A new entry is added to the dictionary, with key "E" and value 1.

  4. In the second for clause, letter is set to "A".

  5. A new entry is added with key "A" and value 1.

Execution proceeds in this manner until all the for clauses are complete. Then the name scrabbleMap is bound to the resulting dictionary.