Basic merge
Input
merge_dicts_by_key([{'id':1,'a':10},{'id':1,'b':20}], 'id')
Output
{1: {'a': 10, 'b': 20}}
Two records share id=1. Fields 'a' and 'b' are merged into the single result for key 1.
Full lesson preview
Group a list of dictionaries by a specified key and merge their fields into combined entries. Conflicting values become lists of unique values in order encountered.
Problem statement
Task
Examples
Input
merge_dicts_by_key([{'id':1,'a':10},{'id':1,'b':20}], 'id')
Output
{1: {'a': 10, 'b': 20}}
Two records share id=1. Fields 'a' and 'b' are merged into the single result for key 1.
Input format
Output format
Constraints
Samples
Input
merge_dicts_by_key([{'id':'x','v':1},{'id':'x','v':2},{'id':'y','v':3}], 'id')
Output
{'x': {'v': [1, 2]}, 'y': {'v': 3}}
Key 'x' had two different v values so they are collected into a list; 'y' had a single value.