Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Group items by two attributes

Organize a list of item dictionaries into a nested mapping keyed by two attributes.

Python practice30 minList & Dictionary PatternsAdvancedLast updated March 20, 2026

Problem statement

Given a list of dictionaries (items) and two keys (key1, key2), produce a nested dict structure grouping items first by key1 then by key2. Only include items that contain both keys. The output should be a dict: {value1: {value2: [item_dicts]}}. The original item dictionaries should not be modified; the grouped lists should contain references to the original dict objects.

Task

Write a function that groups items into a nested dictionary where the first key is the value of key1 and the second key is the value of key2; values are lists of items that match both keys.

Examples

Group fruits by type then color

Input

group_by_two([{'type':'fruit','color':'red','name':'apple'},{'type':'fruit','color':'yellow','name':'banana'},{'type':'vegetable','color':'green','name':'lettuce'}],'type','color')

Output

{'fruit': {'red': [{'type': 'fruit', 'color': 'red', 'name': 'apple'}], 'yellow': [{'type': 'fruit', 'color': 'yellow', 'name': 'banana'}]}, 'vegetable': {'green': [{'type': 'vegetable', 'color': 'green', 'name': 'lettuce'}]}}

Items are grouped first by 'type' then by 'color'.

Input format

A list of dictionaries 'items', and two strings 'key1' and 'key2'.

Output format

A nested dictionary mapping values of key1 to dictionaries mapping values of key2 to lists of item dicts.

Constraints

Items missing either key1 or key2 should be ignored. Preserve insertion order: the outer keys follow the first appearance of each value in items; inner lists preserve item order.

Samples

Sample 1

Input

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

Output

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

Grouping numeric keys preserves numeric key types.