combine 2 lists into dictionary python code example
Example 1: create dictionary python from two lists
>>> keys = ['a', 'b', 'c']
>>> values = [1, 2, 3]
>>> dictionary = dict(zip(keys, values))
>>> print(dictionary)
{'a': 1, 'b': 2, 'c': 3}
Example 2: convert two lists to a single dictionary python
key_list = ['red', 'green', 'blue']
value_list = [1, 2, 3]
my_dict = {}
for key in key_list:
for value in value_list:
my_dict[key] = value
value_list.remove(value)
break
print(my_dict)
Example 3: 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)
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)