6.1 Using enumerate()
We've already looked at looping through keys
, values
, and items
in dictionaries. Now let's take a closer look at the enumerate()
function.
The enumerate()
function is useful for iterating over dictionary elements, giving you access to both the indices and the keys and values.
Here are some examples of using enumerate()
with dictionaries:
Iterating over dictionary keys and values with indices
You can use enumerate()
to loop through the keys and values of a dictionary while getting the indices as well.
# Dictionary with personal data
person = {"name": "Alice", "age": 25, "city": "New York"}
# Iterating over dictionary keys and values with indices
for index, (key, value) in enumerate(person.items()):
print(f"Index: {index}, Key: {key}, Value: {value}")
# Prints index, key, and value of each dictionary element
Output:
Index: 0, Key: name, Value: Alice
Index: 1, Key: age, Value: 25
Index: 2, Key: city, Value: New York
Transforming dictionary values using indices
You can use enumerate()
to modify dictionary values based on their index.
# Original dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
# New dictionary with indices in values
indexed_person = {}
for index, (key, value) in enumerate(person.items()):
indexed_person[key] = f"{value}_{index}"
# Assign index as a string to the dictionary value
print(indexed_person)
# Prints dictionary with indices added to values
Output:
{'name': 'Alice_0', 'age': '25_1', 'city': 'New York_2'}
Creating a new dictionary with enumerate()
You can use enumerate()
to create a new dictionary where indices are keys.
# Original dictionary
person = {"name": "Alice", "age": 25, "city": "New York"}
# New dictionary with indices as keys
indexed_person = {index: (key, value) for index, (key, value) in enumerate(person.items())}
print(indexed_person)
# Prints new dictionary with indices as keys
Output:
{0: ('name', 'Alice'), 1: ('age', 25), 2: ('city', 'New York')}
6.2 Dictionary Comprehensions
We've already used List Comprehensions to generate lists and Set Comprehensions to generate sets. Similarly, the comprehension syntax can be used for creating dictionaries. Dictionary Comprehensions allow for more concise and readable code when creating dictionaries.
The basic dictionary comprehension syntax looks like this:
{expression1: expression2 for variable in sequence if condition}
where
-
variable
— a variable that takes the value of each element from the iterable object. -
sequence
— an iterable object (like a list, tuple, string) that the variable iterates over. -
expression1
— an expression for generating dictionary keys. It's usually based on the variable. -
expression2
— an expression for generating dictionary values. -
condition
— (optional) a condition that must be met for an element to be included in the dictionary.
Example 1:
Creating a dictionary with squares of numbers
# Creating a dictionary where keys are numbers from 1 to 5, and values are their squares
squares = {x: x ** 2 for x in range(1, 6)}
print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Example 2:
Creating a dictionary from a list of tuples
# List of tuples containing key-value pairs
pairs = [("name", "Alice"), ("age", 25), ("city", "New York")]
# Generate dictionary from a list of tuples
person = {key: value for key, value in pairs}
print(person) # Output: {'name': 'Alice', 'age': 25, 'city': 'New York'}
Example 3:
Filtering elements when creating a dictionary
# Creating a dictionary where keys are numbers from 1 to 10, and values are their squares
# Only for even numbers
even_squares = {x: x ** 2 for x in range(1, 11) if x % 2 == 0}
print(even_squares) # Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}
Example 4:
Transforming elements when creating a dictionary
# List of strings
words = ["apple", "banana", "cherry"]
# Generate dictionary with keys as strings and values as their lengths
word_lengths = {word: len(word) for word in words}
print(word_lengths) # Output: {'apple': 5, 'banana': 6, 'cherry': 6}
Nested dictionary comprehensions
# List of lists with key-value pairs
nested_pairs = [[("a", 1), ("b", 2)], [("c", 3), ("d", 4)]]
# Generate dictionary from a nested list
nested_dict = {key: value for sublist in nested_pairs for key, value in sublist}
print(nested_dict) # Output: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Combined methods
You can combine different methods of creating dictionaries for more complex situations.
# Merging multiple dictionaries into one
dict1 = {"name": "John", "age": 30}
dict2 = {"city": "New York", "country": "USA"}
combined_dict = {**dict1, **dict2}
print(combined_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York', 'country': 'USA'}
Using the **
operator in front of a dictionary name allows you to unpack its elements as if they were listed out. Thus, the expression {**dict1, **dict2}
effectively merges elements of both dictionaries.
GO TO FULL VERSION