Python Dictionary Comprehension is a concise and elegant way to create dictionaries in Python using a single line of code. It enables developers to write more readable and efficient code when building dictionaries based on existing iterables like lists, sets, or other dictionaries. This powerful feature simplifies the syntax and improves performance, making it a preferred approach in many Python programming scenarios.
The basic syntax of Python Dictionary Comprehension is:
{key_expression: value_expression for item in iterable if condition}
This is similar to list comprehension but with key-value pairs instead of single elements.
numbers = [1, 2, 3, 4, 5] squares = {x: x**2 for x in numbers} print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
| Traditional Method | Dictionary Comprehension |
|---|---|
|
|
keys = ['name', 'age', 'city'] values = ['Alice', 25, 'New York'] info = {k: v for k, v in zip(keys, values)} print(info) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
marks = {'John': 75, 'Emily': 55, 'Anna': 90} passed = {k: v for k, v in marks.items() if v >= 60} print(passed) # Output: {'John': 75, 'Anna': 90}
original = {'a': 1, 'b': 2, 'c': 3} swapped = {v: k for k, v in original.items()} print(swapped) # Output: {1: 'a', 2: 'b', 3: 'c'}
temperatures_c = {'Monday': 30, 'Tuesday': 32, 'Wednesday': 31} temperatures_f = {day: (temp * 9/5) + 32 for day, temp in temperatures_c.items()} print(temperatures_f) # Output: {'Monday': 86.0, 'Tuesday': 89.6, 'Wednesday': 87.8}
You can use if-else logic within the comprehension.
nums = range(5) parity = {x: ('even' if x % 2 == 0 else 'odd') for x in nums} print(parity) # Output: {0: 'even', 1: 'odd', 2: 'even', 3: 'odd', 4: 'even'}
Python Dictionary Comprehension is a valuable feature that allows for clean, efficient, and readable creation of dictionaries in Python. When used properly, it can streamline code and reduce the need for verbose loops. By mastering this concept, developers can write more expressive and Pythonic code, improving both speed and clarity.
Copyrights © 2024 letsupdateskills All rights reserved