Python Dictionary Key/Value Swap

0
12K

You can change the keys and values in a dictionary using a loop and items(). This can be helpful if the key doesn't exist in the dictionary, but the value exist. Here's an example:

d = {'key1': 'val1', 'key2': 'val2', 'key3': 'val3'}

d_swap = {v: k for k, v in d.items()}
print(d_swap)
# {'val1': 'key1', 'val2': 'key2', 'val3': 'key3'}
Search
Categories
Read More
Climbing
Scaling New Heights: The Thrilling World of Recreational Climbing
Scaling New Heights: The Thrilling World of Recreational Climbing Introduction: In the realm of...
By Leonard Pokrovski 2024-05-09 10:04:05 0 15K
Business
What Are the Main Skills and Techniques Needed for Conflict Resolution?
Effective conflict resolution relies on a combination of interpersonal skills and proven...
By Dacey Rankins 2025-08-04 18:28:48 0 3K
Rural Living
Rural Living: The Benefits and Challenges of Life in the Countryside
Rural living has long been romanticized in literature and media, often depicted as a serene...
By Dacey Rankins 2024-10-18 19:34:56 0 25K
Social Issues
Citizen Kane. (1941)
Following the death of publishing tycoon Charles Foster Kane, reporters scramble to uncover the...
By Leonard Pokrovski 2023-01-14 21:59:59 0 25K
Personal Finance
When Can—and Should—I Retire?
When Can—and Should—I Retire? Understanding the “Right Time” Through...
By Leonard Pokrovski 2025-11-24 15:22:37 0 1K

BigMoney.VIP Powered by Hosting Pokrov