[Python] How to Swap Dictionary Keys and Values: Using Dictionary Comprehension

In a Python dictionary, you may sometimes want to reverse the relationship between Keys and Values. This is useful when you want to identify a Key based on its Value, known as a “reverse lookup,” rather than the standard search (Key to Value).

This article explains how to implement this efficiently using Dictionary Comprehension.

目次

The Problem to Solve

Dictionaries are typically optimized for one-way searches: “Key → Value”. However, in data analysis or network processing, there are scenes where you need to reference “Value → Key”.

Here, we will create a reverse lookup dictionary that allows searching for a Domain Name using an IP Address, using a correspondence table of domains and IPs as an example.

Implementation Example: Reverse DNS Lookup

We will reverse a dictionary that holds Domain Names as Keys and IP Addresses as Values.

Source Code

# Dictionary mapping Domain Names (Key) to IP Addresses (Value)
dns_forward_lookup = {
    "example.com": "93.184.216.34",
    "google.com": "142.250.196.14",
    "python.org": "45.55.99.72"
}

# Swap keys and values using dictionary comprehension
# Syntax: {new_key: new_value for original_key, original_value in dict.items()}
dns_reverse_lookup = {ip: domain for domain, ip in dns_forward_lookup.items()}

# Check the results
print("--- Original Dictionary (Domain -> IP) ---")
print(dns_forward_lookup)

print("\n--- Swapped Dictionary (IP -> Domain) ---")
print(dns_reverse_lookup)

# Example of reverse lookup
target_ip = "142.250.196.14"
if target_ip in dns_reverse_lookup:
    print(f"\nThe domain for IP {target_ip} is {dns_reverse_lookup[target_ip]}.")

Execution Result

--- Original Dictionary (Domain -> IP) ---
{'example.com': '93.184.216.34', 'google.com': '142.250.196.14', 'python.org': '45.55.99.72'}

--- Swapped Dictionary (IP -> Domain) ---
{'93.184.216.34': 'example.com', '142.250.196.14': 'google.com', '45.55.99.72': 'python.org'}

The domain for IP 142.250.196.14 is google.com.

Explanation

Syntax of Dictionary Comprehension

The syntax {value: key for key, value in d.items()} creates a new dictionary by looping through each element of the original dictionary d and reversing the key and value. The items() method is essential here to retrieve pairs of (key, value).

Important Note: Duplicate Values

Dictionary keys must be unique. If the original dictionary has “different keys with the same value” (duplicate values), swapping them will cause data loss. The later element processed will overwrite the earlier one.

# Example with duplicate values
scores = {"Alice": 80, "Bob": 80}

# When swapped...
reversed_scores = {score: name for name, score in scores.items()}
# Result: {80: 'Bob'} (Alice's info is lost)

If the values in the source dictionary are not guaranteed to be unique, this method can lead to data loss. In such cases, you need a different design, such as holding values in a list (e.g., using defaultdict(list)).

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次