![]() |
VOOZH | about |
Dictionary comprehension is used to create a dictionary in a short and clear way. It allows keys and values to be generated from a loop in one line. This helps in building dictionaries directly without writing multiple statements.
Example: This example creates a dictionary where numbers from 1 to 5 are used as keys and their squares are stored as values.
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Explanation:
{key: value for (key, value) in iterable if condition}
This method creates a dictionary by pairing each item from one list with the matching item from another list using zip().
{'a': 1, 'c': 3, 'b': 2, 'e': 5, 'd': 4}
The fromkeys() method creates a dictionary by taking a group of keys and assigning the same value to all of them.
{0: True, 1: True, 2: True, 3: True, 4: True}
Example 1: This example demonstrates creating a dictionary by transforming and repeating characters from a string.
{'C': 'ccc', 'O': 'ooo', 'D': 'ddd', 'I': 'iii', 'N': 'nnn', 'G': 'ggg'}
Example 2: This example maps a list of fruits to their name lengths
{'apple': 5, 'banana': 6, 'cherry': 6}
We can include conditions in a dictionary comprehension to filter items or apply logic only to specific values. This allows us to create dictionaries more selectively.
{0: 0, 8: 512, 2: 8, 4: 64, 6: 216}
We can also create dictionaries within dictionaries using nested dictionary comprehensions. This is useful when each key maps to another dictionary of related values.
{'G': {'G': 'GG', 'F': 'GF'}, 'F': {'G': 'FG', 'F': 'FF'}}