← Back to all snippets
PYTHON

Creating Dictionaries with Comprehensions

Efficiently create and transform dictionaries in Python using concise dictionary comprehensions, perfect for processing data and API responses.

# Example 1: Creating a dictionary from a list of items
items = ['apple', 'banana', 'cherry']
item_prices = {item: len(item) * 1.5 for item in items}
# item_prices will be {'apple': 7.5, 'banana': 9.0, 'cherry': 9.0}

# Example 2: Filtering and transforming an existing dictionary
stock_data = {'apple': 100, 'banana': 0, 'orange': 50, 'grape': 200}
available_stock = {fruit: quantity for fruit, quantity in stock_data.items() if quantity > 0}
# available_stock will be {'apple': 100, 'orange': 50, 'grape': 200}

# Example 3: Reversing keys and values (if values are hashable)
status_codes = {200: 'OK', 404: 'Not Found', 500: 'Internal Server Error'}
code_names = {name: code for code, name in status_codes.items()}
# code_names will be {'OK': 200, 'Not Found': 404, 'Internal Server Error': 500}
How it works: Dictionary comprehensions provide a clean and efficient way to create new dictionaries or transform existing ones. They follow the structure `{key_expression: value_expression for item in iterable if condition}`. This syntax is highly readable and performs better than traditional loop-based dictionary construction, making it ideal for data manipulation tasks common in web development, such as processing API payloads or generating structured responses.

Need help integrating this into your project?

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

Hire DigitalCodeLabs