![](/img/trans.png)
[英]Add key and value of one list of dictionaries to another list of dictionaries
[英]Fastest way to change a key value in list of dictionaries base on another list of dictionaries
例如:我有 2 个字典列表
dictA = [{"Cases": 1, "vertical": 5, "horizontal": 10}, {"Cases": 2, "vertical": 7, "horizontal": 3},{"Cases": 3, "vertical": 2, "horizontal": 9},{"Cases": 4, "vertical": 3, "horizontal": 6}]
dictB = [{"Cases": 1, "vertical": 7, "horizontal": 8},{"Cases": 3, "vertical": 6, "horizontal": 12}]
我需要用 dictB 中的 Cases 替换 dictA 列表中“案例”= 1和3的字典,我有:
for di in dictB:
for d in dictA:
if d["Cases"] == di["Cases"]:
d["vertical"] = di["vertical"]
d["horizontal"] = di["horizontal"]
有没有更好或更快的方法来做到这一点?
您可以使用临时结构,其中键是Case
值是来自dictB
的数据,以避免双重迭代
dictA = [{"Cases": 1, "vertical": 5, "horizontal": 10}, {"Cases": 2, "vertical": 7, "horizontal": 3},
{"Cases": 3, "vertical": 2, "horizontal": 9}, {"Cases": 4, "vertical": 3, "horizontal": 6}]
dictB = [{"Cases": 1, "vertical": 7, "horizontal": 8}, {"Cases": 3, "vertical": 6, "horizontal": 12}]
tmp_b = {x['Cases']: x for x in dictB}
print(tmp_b) # {1: {'Cases': 1, 'vertical': 7, 'horizontal': 8}, 3: {'Cases': 3, 'vertical': 6, 'horizontal': 12}}
for d in dictA:
d.update(tmp_b.get(d['Cases'], {}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.