【问题标题】:Python functions for nested dictionary用于嵌套字典的 Python 函数
【发布时间】:2021-04-01 03:02:22
【问题描述】:

给定一本字典:

dic = {
    2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311},
    7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},
    8: {'r': 0.1, 's': 0.2}

我希望将输出作为字典,键为 'a''p'、...,并将它们的值作为嵌套字典中的值相加

预期输出:

{'p': 0.025 , 'a' 0.09811 ....}

【问题讨论】:

  • 欢迎来到 SO!请拨打tour。你有什么问题?请edit澄清。如果您需要提示,请参阅How to Ask
  • dic 上缺少右大括号
  • {k: sum(d.get(k, 0) for d in dic.values()) for d in dic.values() for k in d.keys()}
  • 为什么'p': 0.025 在输出中?不应该是0.225吗?

标签: python dictionary nested


【解决方案1】:

尝试以下方法:

dic = {2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311}, 7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},8:{'r':0.1, 's':0.2}}

res = {}

for d in dic.values():
    for k, v in d.items():
        res[k] = res.get(k, 0.0) + v

print(res) # {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09811, 'r': 0.28600000000000003, 's': 0.348, 'd': 0.145}

特别是,dict.get(key, value) 如果存在后者,则返回 dict[key],否则返回 value

【讨论】:

    【解决方案2】:

    Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

    使用collections.Counter

    from collections import Counter
    
    dic = {2: {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09311},
           7: {'r': 0.186, 's': 0.148, 'd': 0.145, 'a': 0.005},
           8: {'r': 0.1, 's': 0.2}}
    
    res = dict(sum([Counter(d) for d in dic.values()], Counter()))
    print(res)
    

    输出:

    {'p': 0.225, 'i': 0.159, 'e': 0.116, 'c': 0.098, 'a': 0.09811, 'r': 0.28600000000000003, 's': 0.348, 'd': 0.145}
    

    【讨论】:

      猜你喜欢
      • 2016-01-01
      • 2021-12-04
      • 2013-08-01
      • 1970-01-01
      • 2018-05-31
      • 2011-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多