Scrollable Nav Bar

Python Dictionary Comprehensions

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]

What Is a Dictionary Comprehension?

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:

  • It uses curly braces {} because the output is a dictionary.
  • It must produce both a key and a value, separated by a colon :.
  • It can optionally include conditions (filters), which you’ll see later.

Building a Dictionary from a List of Tuples

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")
]

Approach 1: Using Indexing

You can create a dictionary by indexing into each tuple:

animals = {item[0]: item[1] for item in animal_list}
print(animals)

Expected output:

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]


The Cleaner Way: Tuple Unpacking

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 key
  • value becomes the dictionary value

This is the style you’ll see most often in real code.

[ Compare indexing vs unpacking side-by-side]


Understanding “What’s Between 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.


A Common Error: Unpacking the Wrong Number of Values

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:

How to fix it:

  • Use the correct number of variables: for key, value in ...
  • Or change your data structure so each element contains the correct number of values.

[Show the error message in a console or notebook]


Using keys(), values(), and items()

Dictionaries aren’t just about looking things up—Python provides convenient “views” of dictionary content:

  • animals.keys() → view of keys
  • animals.values() → view of values
  • animals.items() → view of (key, value) pairs

The 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.


Converting a Dictionary Back to a List

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:

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())]


Creating a New List Structure from a Dictionary

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:

This pattern is extremely practical:

  • It turns dictionary data into a list of objects
  • The output is ready for JSON serialization
  • You can rename fields (name, sound) to match what your app or API expects

Adding Conditions (Filtering) in Dictionary Comprehensions

Just 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.


Transforming Values

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:

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:

When you start thinking in transformations, comprehensions become a compact “data formatting tool” inside your code.


Readability Tips for Professionals

Dictionary comprehensions are powerful, but readability matters—especially in team projects.

Use a dictionary comprehension when:

  • The logic is short and clear
  • You’re doing a simple transformation or filter
  • It’s easier to read than a multi-line loop

Prefer a regular loop when:

  • The transformation requires multiple steps
  • You need complex conditional branches
  • You want to add debug prints or comments

A good rule: if the comprehension doesn’t read cleanly in one pass, convert it into a normal loop.


Practice Exercise

Try these on your own:

  1. From a list of tuples like [("IN", "India"), ("US", "United States")], build a dictionary.
  2. From a dictionary of product prices, build a new dictionary with prices after applying 18% GST.
  3. Convert a dictionary into a list of dictionaries using keys "key" and "value".

Summary

Dictionary comprehensions let you generate dictionaries quickly and cleanly from iterable data. The key ideas are:

  • Use {key: value for ...} to create dictionaries
  • Use tuple unpacking (for key, value in ...) for cleaner code
  • Use items() when you need to iterate over key–value pairs
  • Combine dictionary and list comprehensions to reshape data for APIs and real-world formats