如果键匹配,如何在对两个字典进行相同值的加法运算的同时合并两个字典? [英] How can I merge merge two dictionries while performing addition operation on same on its values, if the keys match?

查看:220
本文介绍了如果键匹配,如何在对两个字典进行相同值的加法运算的同时合并两个字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下数据:当前

现在,我写了一个代码,返回了这样的字典:历史

Now, I wrote a code that returns a dictionary like this: history

我还有另一本字典,看起来几乎一样,但有更多的嵌套,像这样:最新

I have other dictionary that looks like almost the same with more nesting, like this: latest

现在,如果我有这两个字典,我想将它们合并,以便:

Now, If I have these two dictionaries, I want to merge them such that if:

dict1 = {201: {'U': {'INR': 10203, 'SGD': 10203, 'USD': 10203, 'YEN': 10203},           
               'V': {'INR': 10203, 'SGD': 10203, 'USD': 10203, 'YEN': 10203}}

dict2= {201: {'X': {'GBP': 10203, 'SGD': 10203, 'USD': 10203, 'YEN': 10203},            
              'V': {'INR': 2253, 'SGD': 9283, 'USD': 6353, 'EUR': 6373}}'

我想编写合并dict1和dict2并返回类似内容的函数:

I want to write function which merges dict1 and dict2 and returns something like :

{201: {'U': {'INR': 10203, 'SGD': 10203, 'USD': 10203, 'YEN': 10203},
       'V': {'INR': 12456, 'SGD': 19486, 'USD': 16556, 'YEN': 10203, 'EURO' : 6373},
        'X': {'GBP': 12990, 'SGD': 10203, 'USD': 10203, 'YEN': 10203 }}

如果货币匹配,则基本添加数字,如果货币匹配,则将带有键的金额附加为货币.

Basically add the numbers if the currency matches, and append the amount with key as currency if it does match with any.

如果货币匹配,我希望添加金额(10203、12456等),如果在新字典中看到其他产品(此处为U,V,X),则希望将其添加到字典中,就像其他任何产品一样将其追加.

I wish to add the amount(10203,12456 etc) if currency matches and add to dictionary if other product (U,V,X here)is seen in new dict just append it like any other product.

有帮助吗?

推荐答案

我认为这段代码可以满足您的需求!

I think this code does what you want!

def merge_and_add(dict1, dict2):
    # We loop over the key and value pairs of the second dictionary...
    for k, v in dict2.items():
        # If the key is also found in the keys of the first dictionary, and...
        if k in dict1.keys():
            # If  the value is a dictionary...
            if isinstance(v, dict):
                # we pass this value to the merge_and_add function, together with the value of first dictionary with
                # the same key and we overwrite this value with the output.
                dict1[k] = merge_and_add(dict1[k], v)

            # If the value is an integer...
            elif isinstance(v, int):
                # we add the value of the key value pair of the second dictionary to the value of the first 
                # dictionary with the same key.
                dict1[k] = dict1[k] + v

        # If the key is not found, the key and value of the second should be appended to the first dictionary
        else:
            dict1[k] = v

    # return the first dictionary
    return 

这篇关于如果键匹配,如何在对两个字典进行相同值的加法运算的同时合并两个字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆