Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Build an index mapping from a list

Create an index mapping values of a specified key to lists of positions they appear at in a list of dicts.

Python practice16 minList & Dictionary PatternsIntermediateLast updated March 20, 2026

Problem statement

Given a list of dictionaries items and a string key_name, implement build_index(items, key_name) that scans items and collects the zero-based indices of each dictionary that contains key_name. The function should skip dictionaries that do not contain key_name. The returned dictionary maps each distinct value (items[i][key_name]) to a list of indices (in increasing order) where that value appears. To keep the output deterministic, insert keys in the returned dict ordered by str(key).

Task

Write build_index(items, key_name) that returns a deterministic dictionary mapping each distinct value found at key_name to a list of indices where that value occurs in items.

Examples

Index by name

Input

items = [{'id':1,'name':'a'}, {'id':2,'name':'b'}, {'id':3,'name':'a'}]; key_name = 'name'

Output

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

Value 'a' occurs at indices 0 and 2, 'b' at index 1.

Input format

Two parameters: items (list of dicts) and key_name (string).

Output format

A dict mapping each found value to a list of integer indices.

Constraints

- Skip entries that do not contain key_name. - Do not assume values are comparable; use str(value) for ordering keys in the returned dict while keeping the original values as keys. - The lists of indices must be in ascending order.

Samples

Sample 1

Input

[{'type':'x'}, {'other':2}, {'type':'y'}], 'type'

Output

{'x': [0], 'y': [2]}

Second dict lacks 'type' and is ignored.