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}
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}
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
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us