1>>> keys = ['a', 'b', 'c']
2>>> values = [1, 2, 3]
3>>> dictionary = dict(zip(keys, values))
4>>> print(dictionary)
5{'a': 1, 'b': 2, 'c': 3}
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#initialize lists
2
3key_list = ['red', 'green', 'blue']
4value_list = [1, 2, 3]
5
6#convert lists
7
8my_dict = {}
9for key in key_list:
10 for value in value_list:
11 my_dict[key] = value
12 value_list.remove(value)
13 break
14print(my_dict)
15
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
1l = [{'a': 0}, {'b': 1}, {'c': 2}, {'d': 3}, {'e': 4, 'a': 4}]
2d = {k: v for x in l for k, v in x.items()}
3print(d)
4# {'a': 4, 'b': 1, 'c': 2, 'd': 3, 'e': 4}