Lesson 17: Dict Comprehension

You can also create dictionaries with Dict Comprehension method in Python.

It works very similar to the List Comprehension methods with some minor differences since dictionary elements are consisted of 2 items each as a key:value pair.

Function : n/a

This lesson doesn’t introduce a new function.

Used Where?

Python’s Dict Comprehension method makes custom and tailored dictionary creation a breeze.

It can be used to creat​e dictionaries from lists, tuples, other dictionaries and even range function. It can replace for loop, conditional if statement, map and filter functions in a simple line.

Let’s see some lines that will help you understand this method in detail.

Syntax do(s)

1) Dict Comprehension is made inside the same curly brackets of a dictionary: {}

2) {i:j for i in dict}
is the default syntax where i:j is the key:value pair, second i is the iterator and dict is your iterable.

Syntax don't(s)

1) Don’t use brackets: [] as you would for list comprehension.

Dict comprehension requires curly brackets: {}

Here is a  note to understand how iteration in dictionaries work and avoid confusion before the examples.

Have you ever tried iterating through a dictionary? If not, go ahead and try a simple loop to print each element in a dictionary.

When you try something like:

for i in dictionary:

You will see that only the keys are getting printed. What happens is when dictionaries are iterated, only the keys actually get iterated. If you’d like to get the values for keys you would have to navigate through the keys, for example:

for i in dictionary:

will print the values. While this will print both keys and values:

for i in dictionary:
print(i, dictionary[i])

Make sure you understand this part clearly before proceeding with examples.

Example 1: same key same value

>>> a = [1,2]
>>> dict = {i:i for i in a}
>>> print(dict

{1: 1, 2: 2}

i:i creates a dictionary with same keys and values from the iterable (in this case list named a)

Example 2

>>> a = [1,2]
>>> dict = {i:a for i in a}
>>> print(dict

{1: [1, 2], 2: [1, 2]}

In this case, i:a creates unique keys from the iterable while each time the whole iterable gets mapped to the key as value. It just shows the power of Comprehension tools in Python.

Example 3

>>> a = {“a”:10, “b”:20, “c”:30}
>>> dict = {i:a for i in a}
>>> print(dict

{‘a’: {‘a’: 10, ‘b’: 20, ‘c’: 30}, ‘b’: {‘a’: 10, ‘b’: 20, ‘c’: 30}, ‘c’: {‘a’: 10, ‘b’: 20, ‘c’: 30}}

Same thing with above example, this time with nested dictionary.

Example 4

>>> a = {“a”:10, “b”:20, “c”:30}
>>> dict = {a[i]:i for i in a}
>>> print(dict

{10: ‘a’, 20: ‘b’, 30: ‘c’}

Again something cool, just with  a simple twist we reversed the key value pair.

Example 5

>>> a = {“a”:10, “b”:20, “c”:30}
>>> dict = {a[i]+100:i for i in a}
>>> print(dict)

{110: ‘a’, 120: ‘b’, 130: ‘c’}

Now adding +100 to the keys. The convenience of Dict Comprehensions…

Example 6

How about adding a string to the key and a value to the value.

>>> a = {“a”:10, “b”:20, “c”:30}
>>> dict = {“Letter “+i:a[i]+1000 for i in a}
>>> print(dict

{‘Letter a’: 1010, ‘Letter b’: 1020, ‘Letter c’: 1030}

Example 7

Let’s create a dictionary from a range with the range function and Dict Comprehension. Let’s make the values squares of the keys.

>>> a = range(1,5)
>>> dict = {i:i**2 for i in a}
>>> print(dict

{1: 1, 2: 4, 3: 9, 4: 16}


1- You can also add conditional statements to your Dict Comprehension.

Simply type your statement to the end and Dict Comprehension will do the rest.

Let’s see some examples:

Example 4: Conditional Statement

>>> dict = [1,2,3,4,5,6,7,8,9]
>>> dict2 = {i:i**2 for i in dict if i<4}
>>> print(dict2

{1: 1, 2: 4, 3: 9}

Advanced Concepts (Optional)

1- N/A

Next Lesson:

help() function


John Sloane

Country Life

Emeralds and Ice by Einerssen-Jonn