Create dictionaries using Dictionary Comprehension

Python

28 Oct 2020 | 2 minute read

If you've been coding in Python, you've probably heard about List Comprehensions. If so, Dictionary Comprehensions is a natural extension to what you're already familiar with.

dictcomps are simple use, and only expects an iterable with a key and a value. In the dictcomp example below, we use the iterable name_height and use the value at the first position (name) as the key, and the value at the second position (height) as the value in the dictionary.

name_height = [
    ('Oscar', 183),
    ('Nicole', 179),
    ('Tuffe', 30),
]

my_dict = {key: value for key, value in name_height}
print(my_dict)
{'Oscar': 183, 'Nicole': 179, 'Tuffe': 30}

Using dictcomps is a neat way to create dictionaries which leaves the code more consistent as a common syntax can be used across multiple data structures.