简体   繁体   中英

Fastest way to change a key value in list of dictionaries base on another list of dictionaries

For example: I have 2 list of dictionaries

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

I need to replace the dictionary where "Cases" = 1 and 3 in dictA list with Cases in dictB I have:

for di in dictB:
    for d in dictA:
       if d["Cases"] == di["Cases"]:
           d["vertical"] = di["vertical"]
           d["horizontal"] = di["horizontal"]

is there a better or faster way to do this?

You may use a temporary structure, where the key is Case and the values are the data from dictB , that avois the double iteration

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'], {}))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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