【问题标题】:How can I merge merge two dictionries while performing addition operation on same on its values, if the keys match?如果键匹配,如何在对其值执行加法运算的同时合并两个字典?
【发布时间】:2020-04-17 06:47:39
【问题描述】:

我的数据如下所示: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 }}

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

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

有什么帮助吗?

【问题讨论】:

  • 所有发布的都是程序描述。但是,我们需要您根据How to Ask 页面提出问题。我们无法确定您想从我们这里得到什么。请edit您的帖子包含一个我们可以回答的有效问题。提醒:通过访问help center,确保您知道这里的主题是什么;要求我们为您编写程序、建议和外部链接都是题外话。
  • @PatrickArtner 问题很简单。我想写一个函数来做我提到的。我不知道如何开始。

标签: python dataframe dictionary lambda data-science


【解决方案1】:

我认为这段代码可以满足你的要求!

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 

【讨论】:

  • 我在代码中添加了一些解释,希望对您有所帮助。我知道我重用该功能的部分可能会令人困惑。只需拿起您的字典并尝试一步一步地遵循它。
猜你喜欢
  • 1970-01-01
  • 2017-11-26
  • 2021-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-14
相关资源
最近更新 更多