Answers for "python merge nested dictionaries"

1

python merge dictionaries

def merge_dicts(dict1, dict2):
        """Here's an example of a for-loop being used abusively."""
        return {**dict2, **{k: (v if not (k in dict2) else (v + dict2.get(k)) if isinstance(v, list) else merge_dicts(v, dict2.get(k))) if isinstance(v, dict) else v for k, v in dict1.items()}}
Posted by: Guest on June-17-2021
1

how to merge a list of dictionaries in python

from collections import defaultdict
dict_list = {
	1: [{
			"x": "test_1",
			"y": 1
		},
		{
			"x": "test_2",
			"y": 1
		}, {
			"x": "test_1",
			"y": 2
		}
	],
}
print(dict_list) # {1: [{'x': 'test_1', 'y': 1}, {'x': 'test_2', 'y': 1}, {'x': 'test_1', 'y': 2}]}

data = dict()
for key, value in dict_list.items():
    tmp = defaultdict(int)
    for index, item in enumerate(value):
        tmp[item.get("x") ] += item.get("y")

    for tmp_key, tmp_value in tmp.items():
        data.setdefault(key, []).append(
            {
                "x": tmp_key,
                "y": tmp_value
            }
        )
print(data) # {1: [{'x': 'test_1', 'y': 3}, {'x': 'test_2', 'y': 1}]}

# test 1 values is added together
Posted by: Guest on February-27-2021
0

merge a list of dictionaries python

>>> from collections import ChainMap
>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
>>> dict(ChainMap(*a))
{'b': 2, 'c': 1, 'a': 1, 'd': 2}
Posted by: Guest on October-13-2020

Code answers related to "python merge nested dictionaries"

Python Answers by Framework

Browse Popular Code Answers by Language