0

Есть два словаря

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
  • Пожалуйста, уточните вашу конкретную проблему или приведите более подробную информацию о том, что именно вам нужно. В текущем виде сложно понять, что именно вы спрашиваете. 25 ноя 2021 в 13:47

2 ответа 2

0

можно решить в лоб:

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)
0

Вариант через промежуточный словарь словарей.

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'}]

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.