Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

Python Dictionary

  1. Home
  2. Python Dictionary
  3. Dict Comprehension

Dict Comprehension

Since: Python 3.0(2008)

A dictionary comprehension is a syntax that creates a dictionary in a single line. Similar in form to list comprehensions, it lets you concisely express key-value transformations and filtering.

Syntax

# Basic dictionary comprehension
{key_expr: value_expr for variable in iterable}

# Dictionary comprehension with a condition
{key_expr: value_expr for variable in iterable if condition}

# Generate from an existing dictionary
{key: transform(value) for key, value in dictionary.items()}

Syntax Patterns

PatternDescription
{k: v for k, v in items()}Converts all entries of a dictionary into a new dictionary. Any expression can be used for keys and values.
{k: v for k, v in items() if condition}Creates a dictionary containing only entries that satisfy the condition.
{v: k for k, v in dictionary.items()}Creates a dictionary with keys and values swapped.
{x: x**2 for x in range(n)}Computes keys and values from an iterable such as a sequence of numbers.
dict(zip(keys, values))Creates a dictionary by pairing two lists as keys and values.

Sample Code

sample_dict_comprehension.py
# Create a dictionary that stores the square of each number.
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Outputs: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# Create a dictionary of only even numbers with a condition.
even_squares = {x: x**2 for x in range(1, 11) if x % 2 == 0}
print(even_squares)  # Outputs: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

# Transform the values of an existing dictionary (multiply power levels by 50).
power_levels = {'Son Goku': 9000, 'Vegeta': 8000, 'Krillin': 1500}
super_saiyan = {k: v * 50 for k, v in power_levels.items()}
print(super_saiyan)  # Outputs: {'Son Goku': 450000, 'Vegeta': 400000, 'Krillin': 75000}

# Swap keys and values.
original = {'a': 1, 'b': 2, 'c': 3}
flipped = {v: k for k, v in original.items()}
print(flipped)  # Outputs: {1: 'a', 2: 'b', 3: 'c'}

# Combine two lists with zip() to create a dictionary.
names = ['Son Goku', 'Vegeta', 'Bulma']
scores = [85, 92, 78]
result = {name: score for name, score in zip(names, scores)}
print(result)  # Outputs: {'Son Goku': 85, 'Vegeta': 92, 'Bulma': 78}

# Combine BGM lists with zip() to create a dictionary.
songs = ['Cha-La Head-Cha-La', 'Vegeta no Theme', 'Bulma no Theme']
song_map = {name: song for name, song in zip(names, songs)}
print(song_map)  # Outputs: {'Son Goku': 'Cha-La Head-Cha-La', 'Vegeta': 'Vegeta no Theme', 'Bulma': 'Bulma no Theme'}

# Use a list of strings as keys and their lengths as values.
words = ['python', 'java', 'javascript']
word_lengths = {w: len(w) for w in words}
print(word_lengths)  # Outputs: {'python': 6, 'java': 4, 'javascript': 10}

# Extract a dictionary containing only specific keys.
profile = {'name': 'Son Goku', 'age': 23, 'org': 'Capsule Corporation', 'job': 'Fighter'}
allowed_keys = {'name', 'org'}
filtered = {k: v for k, v in profile.items() if k in allowed_keys}
print(filtered)  # Outputs: {'name': 'Son Goku', 'org': 'Capsule Corporation'}
python3 dict_comprehension.py
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
{2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
{'Son Goku': 450000, 'Vegeta': 400000, 'Krillin': 75000}
{1: 'a', 2: 'b', 3: 'c'}
{'Son Goku': 85, 'Vegeta': 92, 'Bulma': 78}
{'Son Goku': 'Cha-La Head-Cha-La', 'Vegeta': 'Vegeta no Theme', 'Bulma': 'Bulma no Theme'}
{'python': 6, 'java': 4, 'javascript': 10}
{'name': 'Son Goku', 'org': 'Capsule Corporation'}

Overview

Dictionary comprehensions are one of Python's powerful features, allowing you to create a dictionary in a single line by combining a loop with an optional condition. Compared to building a dictionary with a regular for loop, this syntax is concise, readable, and considered Pythonic.

Because any expression can be used for both keys and values, dictionary comprehensions are useful in many situations — transforming existing dictionaries, filtering entries, and creating reverse-lookup dictionaries. If duplicate keys may occur, the last one processed takes precedence. Keys must also be hashable objects (such as strings, numbers, or tuples); lists cannot be used as keys.

For copying and merging dictionaries, see 'dict.copy() / dict() / Merging Dictionaries'.

If you find any errors or copyright issues, please .