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.
Full lesson preview
Create an index mapping values of a specified key to lists of positions they appear at in a list of dicts.
Problem statement
Task
Examples
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
Output format
Constraints
Samples
Input
[{'type':'x'}, {'other':2}, {'type':'y'}], 'type'
Output
{'x': [0], 'y': [2]}
Second dict lacks 'type' and is ignored.