How can I merge merge two dictionries while performing addition operation on same on its values, if the keys match?

一曲冷凌霜 提交于 2020-01-16 19:31:28

问题


I have data that looks like this: current

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

and

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

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.

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.

Any help ?


回答1:


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 


来源:https://stackoverflow.com/questions/59498363/how-can-i-merge-merge-two-dictionries-while-performing-addition-operation-on-sam

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!