![](/img/trans.png)
[英]Upadate list of dictionary from another list of dictionary by nearest date python
[英]Update list of dictionary from another list of dictionary python
list1 = [
{"code": 1, "a": 7, "b": 9, "c": 24},
{"code": 2, "a": 78, "b": 12, "c": 45},
{"code": 3, "a": 3, "b": 5, "c": 16}
]
list2=[
{"code": 1, "a": 45, "b": 21, "c": 24},
{"code": 2, "a": 84, "b": 7, "c": 55}
]
Output:
list1 = [
{"code": 1, "a": 45, "b": 21, "c": 24},
{"code": 2, "a": 84, "b": 7, "c": 55},
{"code": 3, "a": 3, "b": 5, "c": 16}
]
我需要基于list2
使用相同的键"code"
更新list1
。 我试过了:
update_mapping = {k["code"]: k for k in list2}
list1 = [update_mapping.get(k["code"], k) for k in list1]
但它没有用。
与任何查找问题一样,字典是您的朋友。 将您的列表转换为由代码键入的内容:
d1 = {d['code']: d for d in list1}
d2 = {d['code']: d for d in list2}
d1.update(d2)
list1 = list(d1.values())
字典在 Python 3.6+ 中排序,并且update
保留键顺序,所以这将完美地工作。 对于以前的版本,请使用collections.OrderedDict
(在 Python 3.6+ 中仍然可用):
from collections import OrderedDict
d1 = OrderedDict((d['code'], d) for d in list1)
d2 = OrderedDict((d['code'], d) for d in list2)
d1.update(d2)
list1 = list(d1.values())
假设您的列表顺序正确,另一种解决方案是简单地遍历 list1 中的每个项目并使用 list2 中的相应项目更新它:
for item_1, item_2 in zip(list1, list2):
item_1.update(item_2)
还要记住“Mad”所说的关于 python 3.6-的字典中的插入顺序的观点
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.