November 5, 2024

Dictionary Comprehension in Python

Dictionary comprehension is a concise and efficient way to create dictionaries in Python. It allows you to construct dictionaries using a single line of code, similar to list comprehensions, but specifically for creating dictionaries. This method is useful for generating dictionaries from iterable data or transforming data in a clear and readable way.

1. Syntax

{key_expression: value_expression for item in iterable if condition}

The syntax for dictionary comprehension includes:

  • key_expression: The expression used to generate the keys for the dictionary.
  • value_expression: The expression used to generate the values for the dictionary.
  • iterable: An iterable (like a list, tuple, or set) that provides the data for the dictionary.
  • condition (optional): A conditional statement to filter items from the iterable.

2. Examples

2.1 Basic Dictionary Comprehension

# Create a dictionary where the keys are numbers and the values are their squares
squares = {x: x**2 for x in range(5)}
print(squares)  # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

This example creates a dictionary where each key is a number from 0 to 4, and each value is the square of that number.

2.2 Dictionary Comprehension with Condition

# Create a dictionary where the keys are numbers and the values are their squares, but only for even numbers
even_squares = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_squares)  # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}

In this example, the dictionary comprehension includes a condition to only include even numbers.

2.3 Dictionary Comprehension from a List of Tuples

# Convert a list of tuples into a dictionary
tuple_list = [('a', 1), ('b', 2), ('c', 3)]
dictionary = {key: value for key, value in tuple_list}
print(dictionary)  # Output: {'a': 1, 'b': 2, 'c': 3}

This example converts a list of tuples into a dictionary, where each tuple represents a key-value pair.

3. Nested Dictionary Comprehension

You can also use nested dictionary comprehensions to create more complex dictionaries.

3.1 Example of Nested Dictionary Comprehension

# Create a dictionary where each key is a number and each value is a dictionary of its multiplication table
multiplication_table = {x: {y: x*y for y in range(1, 4)} for x in range(1, 4)}
print(multiplication_table)
# Output: {1: {1: 1, 2: 2, 3: 3}, 2: {1: 2, 2: 4, 3: 6}, 3: {1: 3, 2: 6, 3: 9}}

This example creates a dictionary where each key is a number, and the value is another dictionary containing the multiplication table for that number.

4. Summary

Dictionary comprehension in Python provides a powerful and concise way to create dictionaries. It enables you to construct dictionaries in a single line of code by specifying key-value pairs, optionally including conditions and supporting nested comprehensions. This approach enhances code readability and efficiency when dealing with data transformations and dictionary creation.