Neural Mastery
← Practice
Invert a Dictionaryeasy

Invert a Dictionary

easy Python for AI 10–15 min

NumPy allowed · plain Python earns 10 bonus points

Invert a key-to-value dictionary into a value-to-keys reverse index -- the basic logic behind building inverted indexes for search and grouping mappings.

Related Skills

Task

Implement invert_dictionary(mapping): produce an inverted dictionary where each key is a distinct value from mapping, and its value is a sorted list of keys from mapping that held that value. If mapping is empty, return {}.

Function Signature

invert_dictionary(mapping: dict) -> dict

Examples

Example 1: Duplicate Values
Input: mapping = {'a': 1, 'b': 2, 'c': 1}
Output: {'1': ['a', 'c'], '2': ['b']}
Example 2: All Unique Values
Input: mapping = {'x': 10, 'y': 20}
Output: {'10': ['x'], '20': ['y']}

Constraints

  • Libraries are allowed; a plain-Python solution earns 10 bonus points.
  • Each list of keys in the inverted dictionary must be sorted in ascending order.
  • Empty input dictionary returns an empty dictionary {}.
Python3Saved ✓
def invert_dictionary(mapping: dict) -> dict:
"""Invert a dictionary mapping keys to values.

Returns a dictionary mapping each unique value to a sorted list of
keys that mapped to it. Returns an empty dict for an empty input."""
# Your implementation here
pass

Case 1: Duplicate Values
Input: mapping = {'a': 1, 'b': 2, 'c': 1}
Expected: {'1': ['a', 'c'], '2': ['b']}
Case 2: All Unique Values
Input: mapping = {'x': 10, 'y': 20}
Expected: {'10': ['x'], '20': ['y']}