0
0
Pythonprogramming~10 mins

Inverting a dictionary in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to create an empty dictionary for the inverted result.

Python
inverted = [1]
Drag options to blanks, or click blank then click option'
Adict()
B[]
Cset()
D{}
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using square brackets creates a list, not a dictionary.
Using set() creates a set, not a dictionary.
2fill in blank
medium

Complete the code to loop through the original dictionary's items.

Python
for key, value in original.[1]():
    inverted[value] = key
Drag options to blanks, or click blank then click option'
Aitems
Bkeys
Cvalues
Diter
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using keys() only gives keys, not values.
Using values() only gives values, not keys.
3fill in blank
hard

Fix the error in the code to invert the dictionary correctly.

Python
inverted = {}
for k, v in data.items():
    inverted[[1]] = k
Drag options to blanks, or click blank then click option'
Av
Bk
Cdata
Dinverted
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using k as the new key keeps the dictionary the same.
Using data or inverted as keys causes errors.
4fill in blank
hard

Fill the four blanks to create a dictionary comprehension that inverts the dictionary.

Python
inverted = { [1]: [2] for [3], [4] in original.items() }
Drag options to blanks, or click blank then click option'
Avalue
Bkey
Ck
Dv
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Swapping keys and values incorrectly.
Using variable names inconsistently.
5fill in blank
hard

Fill all three blanks to invert the dictionary and handle duplicate values by storing keys in a list.

Python
inverted = {}
for [1], [2] in original.items():
    inverted.setdefault([3], []).append([1])
Drag options to blanks, or click blank then click option'
Akey
Bvalue
Ck
Dv
Attempts:
3 left
๐Ÿ’ก Hint
Common Mistakes
Using the wrong variable names.
Not using setdefault to handle duplicates.