如果关键字匹配,如何在对同一个词典的值执行加法运算时合并两个词典?

2024-04-23 14:55:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的数据:current

现在,我编写了一个返回如下字典的代码:history

我还有另外一个字典,在嵌套更多的情况下看起来几乎相同,比如:latest

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

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合并,返回如下结果:

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

基本上,如果货币匹配,则添加数字;如果与任何货币匹配,则添加带有键的金额作为货币。你知道吗

如果货币匹配,我想加上金额(1020312456等),如果在新词典中看到其他产品(这里是U,V,X),我想加上字典,就像任何其他产品一样。你知道吗

有什么帮助吗?你知道吗


Tags: 数据代码字典产品货币current金额history
1条回答
网友
1楼 · 发布于 2024-04-23 14:55:07

我想这个代码符合你的要求!你知道吗

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 

相关问题 更多 >