Python Lab · Experiment 18
Invert a dictionary read from the user
PythonWeek 4JNTUH R22 · CS206ES
Aim
To write a Python program that reads key-value pairs from the user into a dictionary, and a function that inverts it so that the values become keys and the keys become values. A second function keeps all keys when a value repeats.
Algorithm
- Read n, the number of items. If n is not positive, print a message and stop.
- Repeat n times: read a line with a key and a value separated by a space, and store
d[key] = value. - Define invert(d): make an empty dictionary, and for each key and value in d, store
inverted[value] = key. Return it. - Define invert_all(d): make an empty dictionary, and for each key and value in d, add the key to a list stored under that value. Return it.
- Print the original dictionary and the results of both functions.
Program
def invert(d):
"""Swap keys and values. A repeated value keeps only the last key."""
inverted = {}
for key, value in d.items():
inverted[value] = key
return inverted
def invert_all(d):
"""Swap keys and values, keeping every key in a list."""
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = []
inverted[value].append(key)
return inverted
n = int(input("Enter the number of items: "))
if n <= 0:
print("Please enter a positive number")
else:
d = {}
for i in range(n):
line = input(f"Enter key and value {i + 1}: ").split()
if len(line) != 2:
print("Each line needs exactly one key and one value")
break
key, value = line
d[key] = value
else:
print()
print("Original dictionary:", d)
print("Inverted dictionary:", invert(d))
print("Inverted, all keys :", invert_all(d))Output
All values different
Enter the number of items: 3
Enter key and value 1: apple red
Enter key and value 2: banana yellow
Enter key and value 3: grape green
Original dictionary: {'apple': 'red', 'banana': 'yellow', 'grape': 'green'}
Inverted dictionary: {'red': 'apple', 'yellow': 'banana', 'green': 'grape'}
Inverted, all keys : {'red': ['apple'], 'yellow': ['banana'], 'green': ['grape']}A value repeats
Enter the number of items: 4
Enter key and value 1: apple red
Enter key and value 2: banana yellow
Enter key and value 3: cherry red
Enter key and value 4: lemon yellow
Original dictionary: {'apple': 'red', 'banana': 'yellow', 'cherry': 'red', 'lemon': 'yellow'}
Inverted dictionary: {'red': 'cherry', 'yellow': 'lemon'}
Inverted, all keys : {'red': ['apple', 'cherry'], 'yellow': ['banana', 'lemon']}Recorded by running this exact program. Typed input appears after each prompt.
How it works
Keys of a dictionary must be unique, but values need not be. When two keys share a value, the inverted dictionary can hold that value as a key only once. In the second run, "red" belongs to both apple and cherry; invert stores apple first and then overwrites it with cherry, so apple is lost. invert_all avoids the loss by storing a list of keys for each value.
Values must be hashable to become keys. Here every value is a string, so this is fine; a list value could not be a key.
Since Python 3.7, dictionaries keep the order in which keys were added, so the output order follows the input.
A one-line version of invert is the dictionary comprehension {value: key for key, value in d.items()}.
Common mistakes
Inverting with
inverted[key] = value. This just copies the dictionary. The value must be the new key:inverted[value] = key.Not thinking about repeated values. With a simple swap, only the last key for a value survives. Use a list of keys when values may repeat.
Changing the dictionary while looping over it, for example deleting old keys as new ones are added. Python raises
RuntimeError. Build a new dictionary.Reading the key and value with
input().split()and not checking that there are exactly two words. A line with one word then fails when unpacking.
Viva questions
Try to answer each one aloud before you open it.
What does it mean to invert a dictionary?
To build a new dictionary where each value of the old one becomes a key, and the matching old key becomes its value.
What happens when the original dictionary has two keys with the same value?
A dictionary key can appear only once, so a simple swap keeps only one of the keys (the last one stored). To keep all of them, store a list of keys for each value.
What does d.items() return?
A view of the dictionary's (key, value) pairs, which can be looped over as tuples.
Can any value be used as a dictionary key?
No. Keys must be hashable, which means immutable types such as numbers, strings and tuples. Lists and dictionaries cannot be keys.
When does the else block of a for loop run?
When the loop finishes all its passes without a
break. Here it prints the result only if every line was read correctly.