Lesson guide
What this Python exercise practices
Invert a One-to-One Dictionary is a intermediate practice lesson that focuses on lists, iteration, filtering. It is designed to be solved in about 17 minutes with examples, starter code, and test feedback.
Prerequisites
- Python variables
- List values
- Basic indexing
Difficulty and time
- Level
- Intermediate
- Estimated time
- 17 minutes
Practice path
Summary
Create the inverse of a mapping: values become keys and keys become values (as lists) to handle duplicate values.
Problem statement
Given a dictionary where multiple keys may map to the same value, invert the mapping so that each value becomes a key mapping to a list of original keys. Preserve the order of original keys as they appear during iteration of the input dictionary. Return the inverted dictionary. Values in the input are guaranteed to be hashable.
Task
Write a function that inverts a dictionary by turning each original value into a key and collecting all original keys that mapped to it into a list, preserving original key order.
Examples
Simple inversion with duplicates
Input
invert_dict({'a': 1, 'b': 2, 'c': 1})
Output
{1: ['a', 'c'], 2: ['b']}
Explanation
Value 1 appears for 'a' then 'c', so inverted[1] is ['a', 'c']; 2 maps to ['b'].
Input format
A dictionary with hashable values.
Output format
A dictionary where each value from the input is a key and maps to a list of original keys.
Constraints
Input values are hashable. If input is empty, return an empty dictionary. Preserve original key order for lists.
Samples
Sample input 0
{'x': 'apple', 'y': 'banana', 'z': 'apple'}
Sample output 0
{'apple': ['x', 'z'], 'banana': ['y']}
Explanation 0
Keys 'x' and 'z' both had value 'apple', so they are collected under 'apple'.
AI assistant
Ask me anything!
Need help? I can explain the core idea behind this problem, review your current code, and give targeted hints. Use “Teach Theory” for the concept, “Get AI hint” for a quick scaffold nudge, or ask a specific question below.
Chat history is temporary and will not be saved.
Free preview includes 1 Teach Theory response and 1 AI hint per unlocked preview lesson.