PYTHON

Efficient Data Transformation with Dictionary Comprehension

Master Python's dictionary comprehension for concisely creating new dictionaries or transforming existing data. Learn to filter, map, and restructure data with elegant one-liners.

# Example 1: Creating a dictionary from a list of key-value pairs
items = [('apple', 1), ('banana', 2), ('orange', 3)]
item_dict = {key: value for key, value in items}
print(f"Dictionary from list of pairs: {item_dict}")

# Example 2: Creating a dictionary from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
person_dict = {k: v for k, v in zip(keys, values)}
print(f"Dictionary from two lists: {person_dict}")

# Example 3: Filtering and transforming an existing dictionary
prices = {'apple': 1.5, 'banana': 0.75, 'orange': 1.2, 'grape': 2.0}
expensive_fruits = {fruit: price for fruit, price in prices.items() if price > 1.0}
print(f"Expensive fruits (price > 1.0): {expensive_fruits}")

# Example 4: Modifying values in a dictionary
discounted_prices = {fruit: price * 0.9 for fruit, price in prices.items()}
print(f"Discounted prices (10% off): {discounted_prices}")

# Example 5: Inverting a dictionary (values become keys, keys become values)
# Be careful: values must be unique to become keys!
fruit_codes = {'apple': 'A001', 'banana': 'B002', 'orange': 'O003'}
code_fruits = {code: fruit for fruit, code in fruit_codes.items()}
print(f"Inverted dictionary: {code_fruits}")

# Example 6: Creating a dictionary with squared values
numbers = [1, 2, 3, 4, 5]
squared_dict = {num: num**2 for num in numbers}
print(f"Numbers and their squares: {squared_dict}")
How it works: Dictionary comprehension provides a concise and readable way to create dictionaries in Python. It allows you to build a new dictionary by iterating over an iterable, applying transformations, and optionally filtering elements, all within a single line. This powerful feature is highly useful for web developers when processing data from APIs, databases, or user input, enabling efficient mapping, filtering, and restructuring of data into a dictionary format without verbose loops.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs