0
0
PythonConceptBeginner · 3 min read

What is Dictionary Comprehension in Python: Simple Explanation

Dictionary comprehension in Python is a concise way to create dictionaries using a single for loop inside curly braces. It lets you build a new dictionary by defining keys and values in a clear, readable format.
⚙️

How It Works

Dictionary comprehension works like a recipe for making a dictionary quickly. Imagine you have a list of items and you want to turn each item into a key-value pair in a dictionary. Instead of writing many lines of code to add each pair one by one, dictionary comprehension lets you do it in one simple line.

It uses a for loop inside curly braces {}, where you specify how to create each key and value. This is similar to how you might quickly write a shopping list by saying "for each fruit, write its name and price". The computer follows this instruction to build the dictionary all at once.

💻

Example

This example creates a dictionary where keys are numbers and values are their squares.

python
squares = {x: x**2 for x in range(5)}
print(squares)
Output
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
🎯

When to Use

Use dictionary comprehension when you want to create a dictionary from an existing list or range quickly and clearly. It is great for transforming data, like turning a list of names into a dictionary with name lengths, or filtering items while creating the dictionary.

For example, if you have a list of words and want a dictionary of only those words longer than 3 letters with their lengths, dictionary comprehension makes this easy and readable.

Key Points

  • Dictionary comprehension uses curly braces {} with a for loop inside.
  • It creates key-value pairs in one line, making code shorter and clearer.
  • You can add conditions to include only certain items.
  • It is useful for transforming and filtering data into dictionaries.

Key Takeaways

Dictionary comprehension creates dictionaries quickly using a simple for loop inside curly braces.
It makes code shorter and easier to read compared to building dictionaries with loops and assignments.
You can include conditions to filter which items become dictionary entries.
Ideal for transforming lists or ranges into dictionaries with custom keys and values.