To swap keys and values in a dictionary in Python, you can use a dictionary comprehension. This allows you to create a new dictionary where the keys and values are swapped.
We can swap keys and values in a dictionary in Python using a dictionary comprehension. This example demonstrates how to declare and initialize a dictionary, use a dictionary comprehension to swap the keys and values, and print the resulting dictionary.
For example,
original_dict
with integer keys and string values.original_dict = {
1: 'One',
2: 'Two',
3: 'Three'
}
# Use a dictionary comprehension to swap the keys and values
swapped_dict = {value: key for key, value in original_dict.items()}
# Print the resulting dictionary
print('Swapped dictionary:')
for key, value in swapped_dict.items():
print(f'Key: {key}, Value: {value}')
Swapped dictionary: Key: One, Value: 1 Key: Two, Value: 2 Key: Three, Value: 3
We can swap keys and values in a dictionary with duplicate values in Python by using a dictionary with lists as values to handle duplicates. This example demonstrates how to declare and initialize a dictionary with duplicate values, use a loop to swap the keys and values while handling duplicates, and print the resulting dictionary.
For example,
original_dict
with integer keys and string values, including duplicate values.swapped_dict
to store the swapped key-value pairs, with lists as values to handle duplicates.original_dict = {
1: 'One',
2: 'Two',
3: 'One'
}
# Declare an empty dictionary to store the swapped key-value pairs
swapped_dict = {}
# Use a loop to swap the keys and values
for key, value in original_dict.items():
if value not in swapped_dict:
swapped_dict[value] = []
swapped_dict[value].append(key)
# Print the resulting dictionary
print('Swapped dictionary:')
for key, value in swapped_dict.items():
print(f'Key: {key}, Values: {value}')
Swapped dictionary: Key: One, Values: [1, 3] Key: Two, Values: [2]
In this tutorial, we learned How to Swap Keys and Values in a Dictionary in Python language with well detailed examples.