Applying Dictionary Comprehension in Practice
Now that you understand the basics of dictionary comprehension, let's explore some practical applications and examples.
One common use case for dictionary comprehension is filtering and transforming data. You can use it to create a new dictionary based on specific conditions or to apply a transformation to the values.
## Example: Create a dictionary of even numbers and their squares
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = {num: num ** 2 for num in numbers if num % 2 == 0}
print(even_squares)
## Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
In this example, the dictionary comprehension {num: num ** 2 for num in numbers if num % 2 == 0}
creates a new dictionary where the keys are the even numbers from the numbers
list, and the values are the squares of those numbers.
Inverting Dictionaries
You can use dictionary comprehension to invert the key-value pairs of an existing dictionary, effectively creating a new dictionary with the keys and values swapped.
## Example: Invert a dictionary
person_info = {'Alice': 25, 'Bob': 30, 'Charlie': 35}
inverted_info = {age: name for name, age in person_info.items()}
print(inverted_info)
## Output: {25: 'Alice', 30: 'Bob', 35: 'Charlie'}
In this example, the dictionary comprehension {age: name for name, age in person_info.items()}
creates a new dictionary where the keys are the ages and the values are the corresponding names.
Grouping Data
Dictionary comprehension can also be used to group data based on certain criteria. This can be useful when you need to organize data into categories or buckets.
## Example: Group names by their starting letter
names = ['Alice', 'Bob', 'Charlie', 'David', 'Emily', 'Frank']
name_groups = {letter: [name for name in names if name.startswith(letter)] for letter in set(name[0] for name in names)}
print(name_groups)
## Output: {'A': ['Alice'], 'B': ['Bob'], 'C': ['Charlie'], 'D': ['David'], 'E': ['Emily'], 'F': ['Frank']}
In this example, the dictionary comprehension {letter: [name for name in names if name.startswith(letter)] for letter in set(name[0] for name in names)}
creates a new dictionary where the keys are the unique starting letters of the names, and the values are lists of names that start with each letter.
These are just a few examples of how you can apply dictionary comprehension in practice. The flexibility and conciseness of this feature make it a powerful tool for working with data in Python.