Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Convert pairs into a dictionary of lists

Turn a list of (key, value) pairs into a dictionary mapping keys to lists of their values.

Python practice17 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Given a list of 2-tuples (key, value) pairs, implement pairs_to_dict(pairs) that returns a dictionary mapping each key to a list of values that appeared paired with that key, preserving input order for values. Keys can be of any hashable type. The returned dictionary must be deterministic: insert keys ordered by str(key).

Task

Implement pairs_to_dict(pairs) to collect values for each key into lists, preserving the order of values for each key. Return a dict with keys inserted in order sorted by str(key) for deterministic output.

Examples

accumulate values by key

Input

[('a', 1), ('b', 2), ('a', 3)]

Output

{'a': [1, 3], 'b': [2]}

Values for 'a' are collected in the list [1, 3] in the order encountered.

Input format

A single parameter: pairs (list of 2-tuples).

Output format

A dict mapping each key to a list of values.

Constraints

- Preserve the order of values for each key. - Use the original key objects in the returned dict. - For deterministic output, insert keys ordered by str(key).

Samples

Sample 1

Input

[(1, 'one'), (2, 'two'), (1, 'uno')]

Output

{1: ['one', 'uno'], 2: ['two']}

Integer keys are preserved; lists keep insertion order.