Dictionary abstraction in Python

Introduction

Dict Comprehension is a dictionary abstraction.

Similar to List Comprehension but it creates a dictionary, not a list.

Basic syntax

Instead of creating an empty dictionary and adding each element at the end, you simply define the dictionary and its contents at the same time, following this format:

new_dict = {key_expression: value_expression for member in iterable}

{ key_expr(item): value_expr(item) for item in iterable }

Keep in mind that iterating over values in dictionaries is different from iterating in lists .

Dict Comprehension is best used with the method items()

Example

Let's create a country-capital dictionary and turn it into a capital-country one using Dict Comprehension

country_to_capital = { "Armenia": "Yerevan", "Finland": "Helsinki", "Germany": "Berlin", "Sweden": "Stockholm" } capital_to_country = {capital: country for country, capital in country_to_capital.items()} from pprint import pprint as pp pp(capital_to_country)

python dict_compreh.py

{'Berlin': 'Germany', 'Helsinki': 'Finland', 'Stockholm': 'Sweden', 'Yerevan': 'Armenia'}

The effect of key uniqueness

Since keys must be unique, when using Dict Comprehensions collisions can occur, and of them only the very last ones survive.

Let's create a dictionary from a list of countries. We will use the first letter of the country name as the key

countries = ["Armenia", "Austria", "Germany", "Georgia"] a = {c[0]: c for c in countries} print(a)

python dict_compreh.py

{'A': 'Austria', 'G': 'Georgia'}

Armenia and Germany did not make it into the list because their keys "A" and "G" were overwritten by the same keys from Austria and Georgia.

Complexity

You can create dictionary abstractions of any complexity, but it is better to limit yourself to those that are easy to read.

import os import glob from pprint import pprint as pp file_sizes = {os.path.realpath(p): os.stat(p).st_size for p in glob.glob('*.py')} pp(file_sizes)

python dict_compreh.py

{'/home/andrei/dict_compreh.py': 283, '/home/andrei/subprocess_ex.py': 102, '/home/pydantic_ex.py': 155}

Filtering with if

When using Dict Comprehension, you can apply conditions to select the objects you need.

from math import sqrt from pprint import pprint as pp def is_prime(x): if x < 2: return False for i in range(2, int(sqrt(x)) + 1): if x % i == 0: return False return True prime_square_divisors = {x*x: (1, x, x*x) for x in range(20) if is_prime(x)} pp(prime_square_divisors)

python filtering_compreh.py

{4: (1, 2, 4), 9: (1, 3, 9), 25: (1, 5, 25), 49: (1, 7, 49), 121: (1, 11, 121), 169: (1, 13, 169), 289: (1, 17, 289), 361: (1, 19, 361)}

Article author: Andrei Olegovich