List comprehension nested dictionary Python

Learn all about Python dictionary comprehensions, including how to create dictionaries, using conditionals [if-else statements], and how to nest comprehensions with easy to follow steps and examples!

Dictionary Comprehensions are similar to Python List Comprehensions. If you want to learn about those as well, check out our tutorial here!

Table of Contents

  • What are Dictionaries [dicts] in Python?
  • What are Python Dictionary Comprehensions?
  • Why Use Python Dict Comprehensions?
  • How Do You Write a Dictionary Comprehension in Python?
  • How Do You Add Conditions [if-else statements] to Python Dictionary Comprehensions?
  • Nested Dictionary Comprehension in Python
  • How Do You Use the Enumerate Function with Python Dictionary Comprehensions?
  • Examples of Python Dictionary Comprehensions
  • Warnings with Python Dictionary Comprehensions
  • Conclusion

What are Dictionaries [dicts] in Python?

Dictionaries [or, dicts] in Python are unordered collections of items. Other compound data types [such as lists or tuples] have only a value as an element, a dictionary has a key:value pair as its element.

Dictionaries allow you to easily retrieve values when you know the key.

If you want to learn everything you need to know about dictionaries in Python, check out Real Pythons comprehensive guide to dictionaries.

How Do You Create a Python Dictionary?

All you need to do to create a dictionary in Python is to place items into curly braces, separated by a comma.

Lets create a dictionary for the book Harry Potter and the Philosophers Stone:

hp = { 'title': "Harry Potter and the Philosopher's Stone", 'author': "J.K. Rowling", 'publication': '1988-06-26' }

How to Access Elements from a Python Dictionary?

Instead of using indexing as other container types do, dictionaries use keys. Keys can be used either inside a square bracket or using the get[] method.

The get[] method returns None instead of KeyError when the key is not found.

print[hp['title']] #Output: Harry Potter and the Philosopher's Stone print[hp.get['publication']] #Output: 1988-06-26

What are Python Dictionary Comprehensions?

Python dictionary comprehensions are concise ways to create dictionaries, without the use of for-loops.

If you want to learn more about For Loops in Python, check out our complete guide!

They are similar to list comprehensions in Python. However, instead of creating lists, they create dictionaries.

Why Use Python Dict Comprehensions?

Dictionary comprehensions are often more concise and easier to read than writing complex for-loops to accomplish the same thing.

Every dictionary comprehension can be written as a for-loop [but not every for-loop can be written as a dictionary comprehension.

For-loops, however, are lengthy and can be difficult to follow.

Because they tend to be quite a bit shorter than for-loops, comprehensions make the code more Pythonic.

Dict comprehensions in Python aim to make code more readable, while not requiring you to write an explicit for-loop.

Every dictionary comprehension can be a for-loop [but not every for-loop can be a dictionary comprehension. I'm learning #Python with @datagy.io!
Click to Tweet

How Do You Write a Dictionary Comprehension in Python?

Similar to list comprehensions in Python, dictionary comprehensions follow the pattern below:

Lets explore this in a little more detail:

  • key:value refers to the key value pair you want to create
  • The key and value do not have to be different and can refer to the same value
  • vars refers to the variable in the iterable
  • iterable refers to any python object you can loop over [such as a list, tuple, or string]

Lets try a simple example:

Dictionary Comprehension Example: Creating Squares of Numbers

Imagine you are tasked to create a dictionary for the numbers 1 through 5, where:

  • The key is original number, and
  • The value is the original number squared

We could write the following code:

squares = {i:i**2 for i in [1,2,3,4,5]} print[squares]

This returns the following dictionary:

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

Dictionary Comprehension Example: Changing from Kilograms to Pounds

Imagine we had a dictionary that contained a weights for items in kilograms and we wanted to convert those weights to pounds:

old_weights = { 'book': 0.5, 'milk': 2.0, 'tv': 7.0 } new_weights = {key: value*2.2 for [key, value] in old_weights.items[]} print[new_weights]

This returns the following output:

{'book': 1.1, 'milk': 4.4, 'tv': 15.4}

Check out some other Python tutorials on datagy, including our complete Pandas Pivot Table tutorial and our Ultimate Guide to SQLite3 in Python!

How Do You Add Conditions [if-else statements] to Python Dictionary Comprehensions?

In most pieces of code, conditions are used as solutions to problems. Python Dictionary Comprehensions become even more powerful when we add conditions to them, such as if and if-else statements.

Adding IF Statements to Python Dict Comprehensions

If we had a dictionary that included key-value pairs of, for example, people and their age, we could filter the dictionary to only include people older than 25:

ages = { 'kevin': 12, 'marcus': 9, 'evan': 31, 'nik': 31 } new_ages = {key:value for [key, value] in ages.items[] if value > 25} print[new_ages]

This returns:

{'evan': 31, 'nik': 31}

Lets take a look at how this is written:

dict = {k:v for var in iterable if condition}

The IF statement follows the iterable item.

Adding Multiple IF Statements

If we want to add multiple if statements [similar to a nested if statement in a for-loop], we simply chain them together.

For example, if we wanted to filter our ages list to only include people younger than 25 and having an even age [where the age modulus 2 returns 0], we could write:

ages = { 'kevin': 12, 'marcus': 9, 'evan': 31, 'nik': 31 } younger = {key:value for [key, value] in ages.items[] if value < 25 if value % 2 == 0} print[younger]

This returns the following:

{'kevin': 12}

If we wanted to chain more if statements, we simply write them in order.

Tip: Chaining if statements is the same as creating an AND statement.

Python Dictionary Comprehension If Else

Using IF-ELSE statements can make dictionary comprehensions even more powerful. Using our earlier example, if we wanted to label the ages as odd or even, we could write the following:

ages = { 'kevin': 12, 'marcus': 9, 'evan': 31, 'nik': 31 } oddeven = {key:['odd' if value % 2 == 1 else 'even'] for [key, value] in ages.items[]} print[oddeven]

This returns the following:

{'kevin': 'even', 'marcus': 'odd', 'evan': 'odd', 'nik': 'odd'}

The structure here is a little different. The IF-ELSE statement is applied directly to the value and is placed in brackets. It is used to transform a value, rather than to remove a key-value pair, in this case.

Nested Dictionary Comprehension in Python

The Value in the Key:Value pair can also be another dictionary comprehension.

Say we wanted to have a dictionary that contains keys of the values of 1 through 5, and each value is another dictionary that contains the key multiplied by intervals of 10 from 10 through 50.

This can be accomplished by writing the following:

mutiples = { key1: { key2: key1 * key2 for key2 in range[1, 6] } for key1 in range[10, 60, 10] } print[mutiples]

This returns the following:

{ 10: {1: 10, 2: 20, 3: 30, 4: 40, 5: 50}, 20: {1: 20, 2: 40, 3: 60, 4: 80, 5: 100}, 30: {1: 30, 2: 60, 3: 90, 4: 120, 5: 150}, 40: {1: 40, 2: 80, 3: 120, 4: 160, 5: 200}, 50: {1: 50, 2: 100, 3: 150, 4: 200, 5: 250} }

Nested dictionary comprehensions can be tricky to understand, so dont worry if you dont fully follow this example!

Its important to note that for nested dictionary comprehensions, Python starts with the outer loop and then moves [per item] into the inner loop.

How Do You Use the Enumerate Function with Python Dictionary Comprehensions?

The Python enumerate function is useful for identifying the index of an item in a list, tuple, or string.

This is particularly useful when combined with a dictionary comprehension, as you can create a dictionary that identifies the index or a particular item.

Lets try this with an example. Well create a list of items and can create a dictionary that identifies the index of each item.

Dictionary Comprehension Example: Using the Enumerate Function

names = ['Harry', 'Hermione', 'Ron', 'Neville', 'Luna'] index = {k:v for [k, v] in enumerate[names]} print[index]

This returns the following:

{'Harry': 0, 'Hermione': 1, 'Ron': 2, 'Neville': 3, 'Luna': 4}

This is particularly helpful if we want to know the index of an item. We can them simply use the get[] method we learned earlier to retrieve the index.

If we wanted to flip the key:value pair around, so that the index number is first, we could write:

names = ['Harry', 'Hermione', 'Ron', 'Neville', 'Luna'] index = {k:v for [v, k] in enumerate[names]} print[index]

Which returns the following:

{0: 'Harry', 1: 'Hermione', 2: 'Ron', 3: 'Neville', 4: 'Luna'}
I'm learning #Python dictionary comprehensions with @datagy! Click to Tweet

Examples of Python Dictionary Comprehensions

Extracting a Subset of a Dictionary

If you want to extract a subset of dictionary key:value pairs from a larger dictionary, this is possible with a dictionary comprehension.

Lets take a look at an example. In the code below, we want to extract a, b, c from the larger dictionary.

bigdict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5} smalldict = {k: bigdict[k] for k in ['a', 'b', 'c']} print[smalldict]

This returns the following:

{'a': 1, 'b': 2, 'c': 3}

Remove Items for a Dictionary

We use dictionary comprehensions to remove items from a dictionary as well. Say we have a dictionary that includes ages for people and we wanted to remove two particular people.

ages = { 'kevin': 12, 'marcus': 9, 'evan': 31, 'nik': 31 } ages = {key:ages[key] for key in ages.keys[] - {'marcus', 'nik'}} print[ages]

This returns the following:

{'evan': 31, 'kevin': 12}

Reverse Key:Value in Dictionary

We can use dictionary comprehensions to reverse the key:value items of a dictionary. Take a look at the code below:

dictionary = {'key1': 'value1', 'key2':'value2'} dictionary = {value:key for [key:value] in dictionary}

Lets use an example to demonstrate this:

user = { 'name': 'nik', 'age': 31, 'company': 'datagy' } user_reversed = {v: k for [k, v] in user.items[]} print[user_reversed]

This returns the following:

{'nik': 'name', 31: 'age', 'datagy': 'company'}

Warnings with Python Dictionary Comprehensions

Dictionary comprehensions are very Pythonic in how they written, but can also get far more complicated to read than for-loops. It may be better to write a longer for-loop that makes the code easier to follow, rather than fitting it all on a single line.

Remember, future-readability is important!

Conclusion

Congratulations! You now know everything you need to know about Python dictionary comprehensions! In this post, you learned what dictionaries are, how to write dictionary comprehensions, adding conditionals, nesting comprehensions, and covered off some examples.

If you have any questions, feel free to ask in the comments below or contact us via social media!

If you want to learn more about Python, check out our eBook!

Share via:

  • Facebook
  • Twitter
  • LinkedIn
  • Email
  • More

Video liên quan

Chủ Đề