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
1>>> result = {}
2>>> for d in L:
3... result.update(d)
4...
5>>> result
6{'a':1,'c':1,'b':2,'d':2}
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
1import pandas as pd
2
3l1 = [{'id': 9, 'av': 4}, {'id': 10, 'av': 0}, {'id': 8, 'av': 0}]
4l2 = [{'id': 9, 'nv': 45}, {'id': 10, 'nv': 0}, {'id': 8, 'nv': 30}]
5
6df1 = pd.DataFrame(l1).set_index('id')
7df2 = pd.DataFrame(l2).set_index('id')
8df = df1.merge(df2, left_index=True, right_index=True)
9df.T.to_dict()
10# {9: {'av': 4, 'nv': 45}, 10: {'av': 0, 'nv': 0}, 8: {'av': 0, 'nv': 30}}