Lesson 17: Python Dict Comprehension

Another just as cool (maybe even cooler!) yet lesser known comprehension method after list comprehension is dict comprehension.

Dict Comprehension can be used to create Python dictionaries in one line with a very cool syntax. Sometimes, dict comprehension can achieve what can normally be achieved in many lines with regular syntax. What it does is, it consolidates loops, functions, conditional statements and dictionary additions in a very compact syntax.

Dict comprehension works very similar to List comprehension however there are some differences since dictionary elements consist of 2 items which consists of “key:value” pairs.

Like many concepts in programming, dict comprehension can be explained best with a few examples and mastered best through practicing Python exercises.

Used Where?

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

It can be used to create 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) We can't use brackets for dict comprehension: as [] belongs to list comprehension. Dict comprehension requires curly brackets: {}

A Refresher on Dictionaries and Python Dictionary Syntax

Here is a  note to help understand how iteration in dictionaries work and how to 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:
    print(i)

You will see that only the keys are getting printed. What happens is when dictionaries are iterated, only the keys actually get iterated because they are seen as the main element in a dictionary. If you’d like to get the values for keys you can simply use keys to access their values, for example:

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

This syntax will print the values of a key only. If you actually wanted both the key and its value as a pair you would have to try something like this which will print both keys and values in a dictionary:

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

So, this may seem repetitive if you already know dictionaries however, its good to recall this exact mechanism since it can be confused when  building dictionaries using dict comprehension. Also if you are not very comfortable with Python dictionaries or their methods yet feel free to revisit: 

as you may want to make sure dictionary syntax is clearly before proceeding with the rest of this Python lesson.

Example 1: Dict comprehension value same as key

Let’s start with a simple and straightforward example. We will get each value in a list as keys for our dictionary and just for simplicity and demonstration we will make the key values same as keys. (i:i)

lst = [1,2]
dict = {i:i for i in lst}
print(dict)

{1: 1, 2: 2}

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

Example 2: The whole list as key values

What if we assigned the whole list as key values? what would happen? Since, dictionaries are composite data structures similar to lists they can hold other collectibles inside them. We will end up with something like this:

lst = [1,2]
dict = {i:lst for i in lst}
print(dict)

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

This might not always be practical but we are playing around here for warm up.

In this case, i:lst 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 and possibilities.

Example 3: The whole dictionary as key values

Let’s do another one with a dictionary. In this case, again, the whole dictionary becomes the value for each key. But, did you notice how iteration resulted in key values for the new dictionary’s key values? This is because when we iterate a dictionary we iterate its keys alone.

lst = {"a":10, "b":20, "c":30}
dict = {i:lst for i in lst}
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. Also, we have a Python lesson about Nested Data in Python with examples.

Example 4: Flipping key value pairs in a dictionary using dict comprehension

This one is more like a dictionary example than a dict comprehension example at this point. If you a have recently learned dictionaries I think it’d be a great idea for you to create a dictionary and then trying to build an identical dictionary from it (or flipping values as in this example) without looking at this example.

Technically, you can do this with any example and it’s a great way to increase your practice exposure and gain experience.

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. We also used Ai in this dict comprehension example, lol 😜

Jokes aside, if you are interested in Machine Learning and AI, definitely take a look at our machine learning algorithm tutorials when you feel ready.

Example 5: Dict comprehension adding values to keys

We are exploring multiple approaches to building a dictionary in Python using dict comprehension. In this example you can see how syntax is used in a way to change the value of each key by adding them 100.

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. Again, the convenience of Dict comprehensions syntax is amazing. We’re doing iteration, dictionary assignment, mapping of values all in one compact line. Later in the examples we will even add a conditional statement to the equation.

Example 6: Dict comprehension manipulating both key and value

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}

Something similar to the previous dict comprehension example. These are giving us the opportunity to create neuron path ways to establish a solid knowledge of Python and in this case specifically dict comprehension syntax.

Function : range function

range function is a very practical way to create numerical ranges that can also be used as iterables. range function returns a range object which can directly be iterated or you can also convert them into data structures such as lists, tuples and dictionaries.

Example 7: Dict comprehension values derived from keys

Here using range function’s values only we will create a dictionary. The trick is to apply some kind of mathematical operation to the keys and assign them as key values in the key:value pair. Here is an example:

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

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

What happens here, we take each value in the range, assign them as keys and then square them and assign those values as key values.

Tips

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

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

Let’s see some examples:

Example 8: Dict comprehension with conditional statement

We can also incorporate conditional statements inside our dict comprehension. All we have to do is add a one line if, else statement at the end of the regular dict comprehension (after the iterable).

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}

What happens here is only values smaller than 4 pass the condition to be included in the dict comprehension process.

Function : zip function

Zip function can be used to combine two collections together. We will show an example in which zip function is used to create the iterable collection for key-value pairs in a dict comprehension.

Example 9: Dict comprehension with zip function

It’s common to utilize zip function in loop iterations, list comprehensions and dict comprehensions. Let’s see a dict comprehension example with zip function.

In Python for loop examples, we had this list which we iterated on. Using dict comprehension can you create a dictionary where keys consist of first nest key’s items and values consist of second nested list’s items? 1:”land”, 2:”sea” and so on. 

lst = [[1,2,3], ["land", "sea", "sky"]]

dict = {i:j for i,j in zip(lst[0], lst[1])}
print(dict)

{1: ‘land’, 2: ‘sea’, 3: ‘sky’}

Great! You can check out Python zip function, if you need a refresher on that. 

Advanced Concepts (Optional)

1- When we need to give numbers to collections in Python, enumerate function can be a clean and straightforward solution. All you have to do is apply enumerate to an iterable (such as list or tuple). Enumerate starts counting from zero but this can be changed to any number by passing a second parameter (integer) to the enumerate function.

Function : enumerate function

Enumerate function is a great way to pair Python sequences (or collections) with numbers. Enumerate function returns an iterable enumerate object in Python.

Example 10: Dict comprehension with enumerate function

Let’s say we have a similar list but this time numbers in the first nested list don’t match what we want and they are pretty much useless.

How can we still build a dictionary using dict comprehension and second nested list inside the list?

This time we will demonstrate the usage of enumerate function, enumerate simply gives a collection’s items numbers. Enumerate function starts counting from 0 by default as this is usually the norm with Python indexing but we can alter this option and make it start from 1 by passing a second parameter.

Check out the example:

lst = [[73,1995,-5], ["land", "sea", "sky"]]

dict = {i:j for i,j in enumerate(lst[1], 1)}
print(dict)

{1: ‘land’, 2: ‘sea’, 3: ‘sky’}

Nice! We got the same result by building our own numeration by using enumerate function and we used that iterable (enumerate object) to create a dictionary using a one line dict comprehension implementation.

In this Python lesson we have expanded our Python knowledge to Dict comprehension methods. We’ve seen how to use it to accumulate dictionary key:value pairs in one line without the need of for loops.

We have also shown how dict comprehension can be used to filter keys or values in the same one line without needing conditional statements, filter function or map function.

Finally, we demonstrated other cool ways dict comprehensions can be combined with Python’s built-in functions zip and enumerate to combine multiple collections to use them as iterables in dict comprehensions.

I hope this Python lesson was clear and useful. As always practicing dict comprehension will ensure sustainable learning which you can use to build amazing solutions, services and products. 🙌

Next Lesson: help() function

einerssen-jonn-emeralds-and-ice


John Sloane

Country Life

Emeralds and Ice by Einerssen-Jonn