Python Dictionary Comprehension Examples

Python Dictionary Comprehension Examples

In this tutorial, you will get Python dictionary comprehension examples.

These examples will help you to master dictionary comprehension in Python.

First, let’s discuss what is a dictionary in Python and what is dictionary comprehension.

Terms

What is a dictionary in Python?

A dictionary in Python is an unordered grouping of key-value pairs.

You can use this built-in data type to store data as key-value pairs.

where each key is distinct and mapped to a corresponding value.

Any data type, including strings, integers, floats, lists, tuples, and even other dictionaries, can be used as a value in a dictionary.

You have to use curly braces enclosing key-value pairs separated by commas to represent dictionaries.

Here is an illustration of a Python dictionary:

my_dict = {"name": "John", "age": 30, "city": "New York"}

In this example, “name”, “age”, and “city” are the keys, and “John”, “30,” and “New York” are the corresponding values.

You can use the keys of a dictionary as the index to find the values by doing something like this:

print(my_dict["name"])
print(my_dict["age"])
print(my_dict["city"])

Output

John
30
New York

What is Python Dictionary Comprehension?

Python dictionary comprehension allows you to specify both the keys and the values in a single line of code.

It makes it easy to create a dictionary from an iterable.

It offers a quick and stylish way to build dictionaries in Python.

The syntax for dictionary comprehension in Python is similar to list comprehension.

However, instead of using square brackets [], you use curly braces {} to define a dictionary, and separate the key-value pairs with a colon (:).

The following is the standard Python syntax for dictionary comprehension.

Syntax

{key: value for (key, value) in iterable}

Here, iterable refers to any object that can return an iterator, such as a list, tuple, or string.

The keys and values of the final dictionary are defined by the key and value variables.

Using a list of integers, the following example builds a dictionary where each integer serves as the key and its square serve as the value.

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

Output

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

In this example, each item in the list is denoted by the key num and its corresponding value is num*num, which is its square.

Additionally, you can use conditional statements inside of a dictionary comprehension to exclude specific elements from the iterable in accordance with a condition.

Using a list of strings, the following example builds a dictionary that only contains strings that begin with the letter “a”:

fruits = ["apple", "banana", "cherry", "apricot", "kiwi"]
a_fruits = {fruit: len(fruit) for fruit in fruits if fruit.startswith("a")}
print(a_fruits)

Output

{‘apple’: 5, ‘apricot’: 7}

In this example, we use the len(fruit) function as the value for each key fruit in the resulting dictionary.

However, we only include those fruits in the dictionary that start with the letter “a”.

Now, let’s move on to some Python dictionary comprehension examples so you can understand it better.

Examples

Python Dictionary Comprehension Examples

Python Dictionary Comprehension Example 1: Convert a list of tuples to a dictionary

You can use Python’s dictionary comprehension to turn a list of tuples into a dictionary by following the method.

Solution

my_list = [('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')]
my_dict = {k: v for k, v in my_list}
print(my_dict)

Output

{‘key1’: ‘value1’, ‘key2’: ‘value2’, ‘key3’: ‘value3’}

Explanation

This will take the list of tuples my_list and turn it into a dictionary called my_dict.

Then we iterated through the list of tuples by dictionary comprehension,

which designates the first item as the key and the second item as the value for each tuple.

After that, we added keys and values from the tuples in the resulting dictionary.

Python Dictionary Comprehension Example 2: Create a dictionary with values squared

In this practice problem, you have to create a dictionary with values squared using dictionary comprehension.

To create a dictionary with the values squared using list comprehension in Python, you can use the following syntax.

Syntax

my_dict = {k: v**2 for k, v in my_dict.items()}

With the same keys as the original dictionary but squared values,

this will produce a new dictionary called my_dict

Dictionary comprehension assigns the key to k and the value to v for each pair of key-value pairs in the original dictionary my_dict.items()

Then it creates a new key-value pair with the same key, k, but with the value squared, v**2, in the new dictionary.

Here is how it will work.

Solution

my_dict = {'a': 2, 'b': 3, 'c': 4}
my_dict_squared = {k: v**2 for k, v in my_dict.items()}
print("my_dict :", my_dict)
print("my_dict_squared :", my_dict_squared)

Output

my_dict : {‘a’: 2, ‘b’: 3, ‘c’: 4}
my_dict_squared : {‘a’: 4, ‘b’: 9, ‘c’: 16}

Explanation

In this example, there are three key-value pairs in the original dictionary, my_dict

and there are three key-value pairs in the new dictionary, my_dict_squared

But the values are squared.

Python Dictionary Comprehension Example 3: Filter dictionary by values

You can easily filter a dictionary by values.

All you have to do is to use an if statement along with the dictionary comprehension.

To filter a dictionary by its values using dictionary comprehension in Python, you can use the following syntax.

Solution

my_dict = {'a': 2, 'b': 3, 'c': 4}
filtered_dict = {k: v for k, v in my_dict.items() if v > 2}
print(filtered_dict)

Output

{‘b’: 3, ‘c’: 4}

Explanation

By doing this, the original dictionary my_dict will be transformed into a new dictionary called filtered_dict

That only contains key-value pairs with values greater than 2.

Dictionary comprehension assigns the key to k and the value to v for each pair of key-value pairs in the original dictionary my_dict.items()

A new key-value pair with the same key k and value v is then created in the new dictionary after determining whether the value v is greater than 2 or not.

Python Dictionary Comprehension Example 4: Convert a list to a dictionary with a default value

You can convert a list into a dictionary with a default value.

Create a variable and store the default value in it.

Then pass this variable as a value in dictionary comprehension.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_list = ['a', 'b', 'c']
default_value = 0
my_dict = {k: default_value for k in my_list}
print(my_dict)

Output

{‘a’: 0, ‘b’: 0, ‘c’: 0}

Explanation

The items from the initial list my_list will be used as keys for the new dictionary my_dict

And the default value 0 will be used as the dictionary’s values.

The dictionary comprehension iterates over the items in the original list my_list

And for each item, it assigns the item to k and the default value 0 to default_value.

Then it creates a new key-value pair with the key k and the value default_value in the new dictionary.

Python Dictionary Comprehension Example 5: Swap keys and values

You can swap the keys and values of a dictionary easily with the help of dictionary comprehension.

Let’s see how you can do it.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_dict = {'a': 2, 'b': 3, 'c': 4}
swapped_dict = {v: k for k, v in my_dict.items()}
print(swapped_dict)

Output

{2: ‘a’, 3: ‘b’, 4: ‘c’}

Explanation

This will swap the keys and values from the original dictionary my_dict to create a new dictionary called swapped_dict.

The dictionary comprehension goes through the key-value pairs in the original dictionary my_dict.items() one by one, assigning the key to k and the value to v for each pair.

The value v serves as the key and the key k serves as the value in a new key-value pair.

That we created in the new dictionary.

Python Dictionary Comprehension Example 6: Count the number of occurrences of each character in a string

In this practice problem of dictionary comprehension, you have to count the number of occurrences of each character in a string.

You can count it using the dictionary comprehension.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_str = "hello world"
char_count = {char: my_str.count(char) for char in my_str}
print(char_count)

Output

{‘h’: 1, ‘e’: 1, ‘l’: 3, ‘o’: 2, ‘ ‘: 1, ‘w’: 1, ‘r’: 1, ‘d’: 1}

Explanation

The characters from the string my_str will be used as keys in a new dictionary called char_count

And the number of times each character appears will be used as a value.

The dictionary comprehension goes through the characters in the string my_str character by character.

And for each character, it uses the count() method of strings to create a new key-value pair in the new dictionary with the character as the key and the number of times that character appears in the string as the value.

Python Dictionary Comprehension Example 7: Create a dictionary from two lists

In this practice problem of Python dictionary comprehension, you have to create a dictionary from two lists.

One list will contain all the keys.

While the second list will contain all the values.

Now, you can easily use the list comprehension to create a dictionary out of the two list.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

keys = ['a', 'b', 'c']
values = [1, 2, 3]
my_dict = {keys[i]: values[i] for i in range(len(keys))}
print(my_dict)

Output

{‘a’: 1, ‘b’: 2, ‘c’: 3}

Explanation

In this example, the keys list contains the keys for the dictionary, and the values list contains the values for the dictionary.

In order to access the corresponding elements of both lists,

we iterate over the list indices using the range() function.

Then, using the key from the list of keys and the value from the list of values, we create a new key-value pair in the dictionary.

Python Dictionary Comprehension Example 8: Filter dictionary by keys

In this practice problem, you have to filter a dictionary by keys.

First, create a list of keys that you want to keep in the dictionary.

Then, use dictionary comprehension with an if statement to filter the dictionary by keys.

Give it a try on our free Online Python Compiler before moving to solution.

Solution

my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
keys_to_keep = ['a', 'c']
filtered_dict = {key: value for key, value in my_dict.items() if key in keys_to_keep}
print(filtered_dict)

Output

{‘a’: 1, ‘c’: 3}

Explanation

We created a new dictionary called filtered_dict

And it will only contain key-value pairs from my_dict whose keys are on the keys_to_keep list.

Every key-value pair in my_dict is iterated over by the dictionary comprehension.

And for each key-value pair, it determines whether the key is on the keys_to_keep list.

If the key appears in the list, a new key-value pair with the same key and value as in my_dict is created in the filtered_dict dictionary.

Was this helpful?
YesNo

Related Articles:

Recent Articles:

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x