![](/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.