Skip to main content

Section 15.11 Dictionary Comprehensions

Like lists, dictionaries also support comprehensions as an alternative to dictionary generation with lengthier loops. The format for a dictionary comprehension is as follows
{<key-expression>:<value-expression> for <item> in <sequence> if <condition>}
Make careful note of the use of curly brackets instead of square brackets. These brackets are primarily how Python determines what kind of comprehension you are making. Like list comprehensions, the if clause is optional.
Let’s view an example,
This code takes two separate lists and associates their values in a new dictionary. More specifically, first names are mapped to last names.
Another more complicated example:

Note 15.11.1.

This workspace is provided for your convenience. You can use this activecode window to try out anything you like.
Check your understanding

Checkpoint 15.11.2.

    What is printed by the following statements?
    alist = [4,2,8,6,5]
    dic = {num:num**2 for num in alist if num < 6}
    print(dic)
    
  • [4,2,5]
  • This is the list of keys that will be generated, but it is missing the associated values.
  • {4:16,2:4,8:64,6:36,5:25}
  • This is nearly correct, but has too many values. Look at the if clause.
  • {4:16,2:4,5:25}
  • Yes, this is correct.
  • {4:8,2:4,5:10}
  • These are the correct keys, but pay close attention to the value expression in the code.
You have attempted of activities on this page.