Dictionary comprehensions are a clean, expressive way to create dictionaries from any iterable—lists, tuples, sets, and even other dictionaries. If you’ve used list comprehensions before, dictionary comprehensions will feel familiar: you still iterate over data and build a new structure in a single readable expression.
In this tutorial, you’ll learn how dictionary comprehensions work, how tuple unpacking makes them elegant, how to avoid common mistakes, and how to move back and forth between dictionaries and list-like structures using items()—plus a few practical patterns you can reuse in real projects.
[Output of a simple dictionary comprehension in a Python REPL or Jupyter Notebook]
A dictionary comprehension generates a new dictionary by looping over an iterable and producing key–value pairs.
The general syntax looks like this:
{key_expression: value_expression for item in iterable}
Key points:
{} because the output is a dictionary.:.A very common scenario is receiving data as a list of tuples where each tuple represents a (key, value) pair.
Example:
animal_list = [
("cat", "meow"),
("dog", "bark"),
("cow", "moo")
]
You can create a dictionary by indexing into each tuple:
animals = {item[0]: item[1] for item in animal_list}
print(animals)Expected output:
{'cat': 'meow', 'dog': 'bark', 'cow': 'moo'}Code language: JavaScript (javascript)
This works, but indexing can look a bit mechanical—especially when your tuples have meaningful parts like “key” and “value”.
[ Create animal_list, run indexing-based dictionary comprehension, print output]
Python allows you to unpack values from tuples into multiple variables—as long as the number of variables matches the number of values in each tuple.
That means you can rewrite the same dictionary comprehension more elegantly:
animals = {key: value for key, value in animal_list}
print(animals)This version is easier to read because it describes intent:
key becomes the dictionary keyvalue becomes the dictionary valueThis is the style you’ll see most often in real code.
[ Compare indexing vs unpacking side-by-side]
for and in”A helpful mental model:
Whatever you write between for and in is what each item from the iterable is assigned to.
So, with:
for key, value in animal_list:
...
Each tuple like (“cat”, “meow”) is unpacked into:
key = "cat"value = "meow"That unpacking is exactly what makes the comprehension form possible and clean.
Unpacking is powerful, but it comes with a rule: the number of variables must match the number of values in each item.
For example, if each tuple has two values but you try to unpack into three variables:
animal_list = [("cat", "meow"), ("dog", "bark")]
bad = {a: b for a, b, c in animal_list}
Python will raise an error similar to:
ValueError: not enough values to unpack (expected 3, got 2)
Code language: HTTP (http)
How to fix it:
for key, value in ...[Show the error message in a console or notebook]
Dictionaries aren’t just about looking things up—Python provides convenient “views” of dictionary content:
animals.keys() → view of keysanimals.values() → view of valuesanimals.items() → view of (key, value) pairsThe most useful one for transformations is items().
Example: Getting Key–Value Pairs with items()
animals = {"cat": "meow", "dog": "bark", "cow": "moo"}
pairs_view = animals.items()
print(pairs_view)
This prints a special view object (often displayed as dict_items([...])). It behaves like an iterable of pairs.
Since items() produces something that looks like a list of pairs, you can convert it back into a list of tuples:
animal_list_again = list(animals.items())
print(animal_list_again)
Output:
[('cat', 'meow'), ('dog', 'bark'), ('cow', 'moo')]
Code language: JSON / JSON with Comments (json)
This is useful when you need list-style operations like sorting or sending the data to APIs that expect lists.
[ Convert dictionary to list with list(animals.items())]
Sometimes you don’t want the exact same tuple structure back. Maybe you need a list of dictionaries—one per item—because that format is common in JSON, APIs, and frontend data.
You can do that with a list comprehension over items():
result = [{"name": key, "sound": value} for key, value in animals.items()]
print(result)Output:
[
{'name': 'cat', 'sound': 'meow'},
{'name': 'dog', 'sound': 'bark'},
{'name': 'cow', 'sound': 'moo'}
]
Code language: JavaScript (javascript)
This pattern is extremely practical:
name, sound) to match what your app or API expectsJust like list comprehensions, you can filter items while building the dictionary.
Example: keep only animals whose sound has 4 or fewer characters:
animals = {"cat": "meow", "dog": "bark", "cow": "moo", "lion": "roar"}
short_sounds = {k: v for k, v in animals.items() if len(v) <= 4}
print(short_sounds)
This filter runs for each (k, v) pair.
Dictionary comprehensions aren’t limited to copying data—you can transform it.
Example: Uppercase all sounds
animals = {"cat": "meow", "dog": "bark"}
loud = {k: v.upper() for k, v in animals.items()}
print(loud)
Output:
{'cat': 'MEOW', 'dog': 'BARK'}
Code language: JavaScript (javascript)
Example: Build a dictionary where keys are length of the sound
animals = {"cat": "meow", "dog": "bark", "cow": "moo"}
sound_lengths = {k: len(v) for k, v in animals.items()}
print(sound_lengths)
Output:
{'cat': 4, 'dog': 4, 'cow': 3}
Code language: JavaScript (javascript)
When you start thinking in transformations, comprehensions become a compact “data formatting tool” inside your code.
Dictionary comprehensions are powerful, but readability matters—especially in team projects.
Use a dictionary comprehension when:
Prefer a regular loop when:
A good rule: if the comprehension doesn’t read cleanly in one pass, convert it into a normal loop.
Try these on your own:
[("IN", "India"), ("US", "United States")], build a dictionary."key" and "value".Dictionary comprehensions let you generate dictionaries quickly and cleanly from iterable data. The key ideas are:
{key: value for ...} to create dictionariesfor key, value in ...) for cleaner codeitems() when you need to iterate over key–value pairs