简体   繁体   English

如何在python中添加两个dict的对应元素?

[英]How to add corresponding elements of two dicts in python?

I have two dicts of the following type:我有以下类型的两个字典:

dict1 = {
   "name1": {
        "quantity" : 23,
        "totalCost": 110.0
    }, ......
}
dict2 = {
   "name1": {
        "quantity" : 45,
        "totalCost": 70.0
    },
   "name2": {
        "quantity" : 60,
        "totalCost": 120.0
    }, ......
}

The two dicts CAN have the same dict values or different dict values, while "quantity" and "totalCost" are fixed parameters.两个dict可以有相同的dict值或不同的dict值,而“quantity”和“totalCost”是固定参数。 I want my resultant dict to be the sum of the two as follows:我希望我的结果 dict 是两者的总和,如下所示:

dict1 = {
   "name1": {
        "quantity" : 68,
        "totalCost": 180.0
    },
   "name2": {
        "quantity" : 60,
        "totalCost": 120.0
    }, ......
}

I could use two for loops but I'm finding it very hard to debug for a larger number of nested dicts.我可以使用两个 for 循环,但我发现很难调试大量嵌套的 dicts。 Is there an easier method that performs this update operation?是否有更简单的方法来执行此更新操作?

As "quantity" and "totalCost" are fixed keys of the inside dict, you can simply do this:由于“数量”和“总成本”是内部字典的固定键,您可以简单地这样做:

for k, v in dict2.items():
    if k not in dict1:
        dict1[k] = v
    else:
        dict1[k]["quantity"] += v["quantity"]
        dict1[k]["totalCost"] += v["totalCost"]

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

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