python - Combine dictionaries based on key value -
how combine rows of dictionaries having same keys. instance if have
my_dict_list = [{'prakash': ['confident']}, {'gagan': ['good', 'luck']}, {'jitu': ['gold']}, {'jitu': ['wins']}, {'atanu': ['good', 'glory']}, {'atanu': ['top', 'winner','good']}]
my objective
my_new_dict_list = [{'prakash': ['confident']}, {'gagan': ['good', 'luck']}, {'jitu': ['gold','wins']}, {'atanu': ['good', 'glory','top', 'winner','good']}]
how do in python?
edit: dictionaries in final list must contain repeated values if present in starting list.
a minimalist approach using defaultdict
:
from collections import defaultdict my_dict_list = [{'prakash': ['confident']}, {'gagan': ['good', 'luck']}, {'jitu': ['gold']}, {'jitu': ['wins']}, {'atanu': ['good', 'glory']}, {'atanu': ['top', 'winner','good']}] merged_dict = defaultdict(list) d in my_dict_list: key, value in d.items(): merged_dict[key].extend(value) result = [{key:value} key, value in merged_dict.items()] print(result)
output
[{'prakash': ['confident']}, {'gagan': ['good', 'luck']}, {'atanu': ['good', 'glory', 'top', 'winner', 'good']}, {'jitu': ['gold', 'wins']}]
Comments
Post a Comment