Invert a Dictionary Practice Problem
This data science coding problem helps you practice Data Structures, invert a dictionary, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Data Structures.
- Problem ID: 88
- Problem key: 88-invert-a-dictionary
- URL: https://datacrack.app/solve/88-invert-a-dictionary
- Difficulty: medium
- Topic: Data Structures
- Module: Python Fundamentals
Problem Statement
# š§© Invert a Dictionary
---
### šÆ Goal
Dictionary inversion (swapping keys and values) is a common data transformation. In data science, this appears when reversing label encodings, inverting index mappings, or building reverse lookup tables.
---
### š What Is Inversion?
Swap every key-value pair so values become keys and keys become values:
```
{"a": 1, "b": 2, "c": 3}
ā {1: "a", 2: "b", 3: "c"}
```
For this problem, assume all values are unique (so the inversion is unambiguous).
---
### š» Task
Implement `invert_dict(d)`.
---
### š„ Input
- `d`: dict with unique values
### š¤ Output
- A new dict with keys and values swapped
---
### š§© Starter Code
```python
def invert_dict(d):
"""
Invert a dictionary (swap keys and values).
Args:
d (dict): Dictionary with unique values
Returns:
dict: Inverted dictionary {value: key}
"""
inverted = {}
for key, value in d.items():
# š§ TODO: In inverted, store value as the key and key as the value
pass
return inverted
```
---
### š” Example
```python
invert_dict({"a": 1, "b": 2, "c": 3})
# Expected: {1: "a", 2: "b", 3: "c"}
invert_dict({"name": "Alice", "role": "engineer"})
# Expected: {"Alice": "name", "engineer": "role"}
```
---
### š Key Concepts
- `dict.items()` ā iterate over key-value pairs as tuples
- Dict keys must be **hashable** ā strings, ints, tuples are hashable; lists are not
- In ML: label encoders create `{"cat": 0, "dog": 1}`, and you need `{0: "cat", 1: "dog"}` to decode predictionsStarter Code
def invert_dict(d):
"""
Invert a dictionary (swap keys and values).
Args:
d (dict): Dictionary with unique values
Returns:
dict: Inverted dictionary {value: key}
"""
inverted = {}
for key, value in d.items():
# š§ TODO: In inverted, store value as the key and key as the value
pass
return inverted