【问题标题】:python combining dictionary results with overlapping keyspython将字典结果与重叠键结合起来
【发布时间】:2020-10-16 09:41:14
【问题描述】:

我有一个频率分布字典作为熊猫数据框中的特征列。

我想加入给定一周的字典中的所有键值对并将它们组合起来,以便在一周中重复的单词的频率总和更新新字典的键值对。

例如:

dict{'apple' : 3, 'banana' : 4}
dict{'apple' : 5, 'banana' : 7, 'orange' : 2}

# to become
dict{'apple' : 8, 'banana' : 11, 'orange' : 2}

有没有一种方法可以做到这一点,而不是手动创建新字典并逐项搜索?

【问题讨论】:

    标签: python pandas dictionary


    【解决方案1】:

    dictCounter 的子类是为这样的用例而设计的:

    from collections import Counter
    
    d1 = {'apple' : 3, 'banana' : 4}
    d2 = {'apple' : 5, 'banana' : 7, 'orange' : 2}
    d3 = dict(Counter(d1) + Counter(d2))
    print(d3)
    

    输出:

    {'apple': 8, 'banana': 11, 'orange': 2}
    

    【讨论】:

      【解决方案2】:

      如果你想编写一个没有任何库的脚本,你可以这样解决,但你应该给你的字典一个值:

      a = {'apple' : 3, 'banana' : 4}
      b = {'apple' : 5, 'banana' : 7, 'orange' : 2}
      output = {}
      for i in a:
       output[i]=output.get(i,0)+a[i]
      for i in b:
       output[i]=output.get(i,0)+b[i]
      print(output)
      

      如您所见,我使用 for loop 和 null dict 进行求解

      【讨论】:

        【解决方案3】:

        如果您可以使用 defaultdict 创建 d1(或 d2),则可以消除对第三个字典的需要:

        from collections import defaultdict
        d1 = defaultdict(int, {'apple' : 3, 'banana' : 4})
        d2 = {'apple' : 5, 'banana' : 7, 'orange' : 2}
        
        for key, val in d2.items():
            d1[key] += val
        print(d1)
        
        # output
        defaultdict(<class 'int'>, {'apple': 8, 'banana': 11, 'orange': 2})
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-11-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多