What is Dictionary Comprehension in Python: Simple Explanation
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.
squares = {x: x**2 for x in range(5)}
print(squares)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 aforloop 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
for loop inside curly braces.