1dict1 = {'color': 'blue', 'shape': 'square'}
2dict2 = {'color': 'red', 'edges': 4}
3
4dict1.update(dict2) #if a key exists in both, it takes the value of the second dict
5# dict1 = {'color': 'red', 'shape': 'square', 'edges': 4}
6# dict2 is left unchanged
1def merge_dicts(dict1, dict2):
2 """Here's an example of a for-loop being used abusively."""
3 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()}}
1from collections import defaultdict
2dict_list = {
3 1: [{
4 "x": "test_1",
5 "y": 1
6 },
7 {
8 "x": "test_2",
9 "y": 1
10 }, {
11 "x": "test_1",
12 "y": 2
13 }
14 ],
15}
16print(dict_list) # {1: [{'x': 'test_1', 'y': 1}, {'x': 'test_2', 'y': 1}, {'x': 'test_1', 'y': 2}]}
17
18data = dict()
19for key, value in dict_list.items():
20 tmp = defaultdict(int)
21 for index, item in enumerate(value):
22 tmp[item.get("x") ] += item.get("y")
23
24 for tmp_key, tmp_value in tmp.items():
25 data.setdefault(key, []).append(
26 {
27 "x": tmp_key,
28 "y": tmp_value
29 }
30 )
31print(data) # {1: [{'x': 'test_1', 'y': 3}, {'x': 'test_2', 'y': 1}]}
32
33# test 1 values is added together
1>>> from collections import ChainMap
2>>> a = [{'a':1},{'b':2},{'c':1},{'d':2}]
3>>> dict(ChainMap(*a))
4{'b': 2, 'c': 1, 'a': 1, 'd': 2}
5