Словари в python, добавление значений
Есть два словаря
dict_1 = [{'id': 1, 'value': someValue}, {'id': 2, 'value': someValue2}]
dict_2 = [{'id': 1, 'anotherValue': another}, {'id': 2, 'anotherValue': another}]
как сравнить их ключи, в данном случае id и обьеденить в один чтобы получилось что-то на подобе
result_dict = [{'id': 1, 'value': someValue, 'anotherValue': another}, {'id': 2, 'value': someValue2, 'anotherValue': another}]
Ответы (2 шт):
Автор решения: Zhihar
→ Ссылка
можно решить в лоб:
dict_1 = [{'id': 1, 'value': 11}, {'id': 2, 'value': 12}]
dict_2 = [{'id': 1, 'anotherValue': 13}, {'id': 2, 'anotherValue': 14}]
tmp = {}
for obj in [dict_1, dict_2]:
for elem in obj:
if elem['id'] not in tmp:
tmp[elem['id']] = elem
else:
tmp[elem['id']].update(elem)
res = [value for value in tmp.values()]
print(res)
Автор решения: GrAnd
→ Ссылка
Вариант через промежуточный словарь словарей.
dict_1 = [{'id': 1, 'value': 'someValue'}, {'id': 2, 'value': 'someValue2'}]
dict_2 = [{'id': 1, 'anotherValue': 'another'}, {'id': 2, 'anotherValue': 'another2'}]
d = {x['id']:x.copy() for x in dict_1}
for x in dict_2:
d[x['id']].update(x)
result_dict = list(d.values())
print(result_dict)
[{'id': 1, 'value': 'someValue', 'anotherValue': 'another'},
{'id': 2, 'value': 'someValue2', 'anotherValue': 'another2'}]