简体   繁体   English

在 Python 中比较和更新包含具有唯一键的字典的两个列表

[英]Comparing and updating two lists containing dictionaries with unique keys in Python

I have two lists, both contain dictionaries.I want to compare list_1 with list_2,我有两个列表,都包含字典。我想比较 list_1 和 list_2,

  1. If any values changes in the list_1 according to list_2 we can update that values to list_2.如果 list_1 中的任何值根据 list_2 发生变化,我们可以将该值更新为 list_2。
  2. While comparing both lists, if new dictionary is found on list_1 we can add that dict to list_2.在比较两个列表时,如果在 list_1 上找到新字典,我们可以将该字典添加到 list_2。
  3. While comparing both lists, if a dict is missing in list_1 according to list_2, we can delete that dict from list_2 also.在比较两个列表时,如果根据 list_2 在 list_1 中缺少一个 dict,我们也可以从 list_2 中删除该 dict。

list_1 list_1

list_1 = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00]

list_2 list_2

list_2 = [{'unique_id': 'ABC001', 'key_1': 'Apple', 'price': 80.00}, {'unique_id': 'ABC002', 'key_2': 'Orange', 'price': 70.00}] 

Expected Result预期结果

list_2 = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00}]

There doesn't seem to be any difference between your list_1 and what you posted as the expected result.您的list_1与您发布的预期结果之间似乎没有任何区别。

list_1 = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00}]

list_2 = [{'unique_id': 'ABC001', 'key_1': 'Apple', 'price': 80.00}, {'unique_id': 'ABC002', 'key_2': 'Orange', 'price': 70.00}]
expected_result = [{'unique_id': 'ABC001', 'key_1': 'Apple_New', 'price': 100.00}, {'unique_id': 'ABC003', 'key_3': 'Grapes', 'price': 80.00}]

list_1 == expected_result  # True

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM