python - 嵌套字典理解

标签 python dictionary nested

对于下面的嵌套字典,我想对每个 'ab''bc''cd''de' 键分别。基本上,折叠字典。最好使用 =sum 的理解,但无法找出正确的语法:

{'hot': {'111': {'ab': 1, 'bc': 3, 'cd': 5, 'de': 7}}}
{'hot': {'111': {'ab': 12.5, 'bc': -31, 'cd': 2.5, 'de': 13}}}
{'hot': {'111': {'ab': 10, 'bc': 3, 'cd': 0, 'de': -2}}}

{'hot': {'110': {'ab': -1, 'bc': 0, 'cd': 1, 'de': 1}}}
{'hot': {'110': {'ab': 8, 'bc': 20, 'cd': 41, 'de': 13}}}
{'hot': {'110': {'ab': 1.75, 'bc': 2.3, 'cd': 6, 'de': 0}}}

{'hot': {'109': {'ab': 2.7, 'bc': 24, 'cd': 4, 'de': 5}}}
{'hot': {'109': {'ab': 41, 'bc': 6, 'cd': 12, 'de': 33}}}
{'hot': {'109': {'ab': 32, 'bc': 7, 'cd': 18, 'de': 3.75}}}

{'cold': {'111': {'ab': 25, 'bc': 2, 'cd': 3, 'de': 2.1}}}
{'cold': {'111': {'ab': 5, 'bc': 8, 'cd': 5, 'de': 17}}}
{'cold': {'111': {'ab': -71, 'bc': 42, 'cd': 5, 'de': 16}}}

{'cold': {'110': {'ab': 23, 'bc': 2.4, 'cd': 2.1, 'de': 4.3}}}
{'cold': {'110': {'ab': 11, 'bc': 2.8, 'cd': 4.5, 'de': 2.4}}}
{'cold': {'110': {'ab': 4, 'bc': 5.7, 'cd': 8.7, 'de': 1}}}        

期望的输出:

dict['hot']['111'][AB] = 1 + 12.5 + 10 = 23.5
dict['hot']['111'][BC] = 3 - 31 + 3 = - 25

等等

最佳答案

我假设您的数据在一个列表中,因为有了这个,您会得到您期望的答案。

data = [{'hot': {'111': {'ab': 1, 'bc': 3, 'cd': 5, 'de': 7}}},
{'hot': {'111': {'ab': 12.5, 'bc': -31, 'cd': 2.5, 'de': 13}}},
{'hot': {'111': {'ab': 10, 'bc': 3, 'cd': 0, 'de': -2}}},

{'hot': {'110': {'ab': -1, 'bc': 0, 'cd': 1, 'de': 1}}},
{'hot': {'110': {'ab': 8, 'bc': 20, 'cd': 41, 'de': 13}}},
{'hot': {'110': {'ab': 1.75, 'bc': 2.3, 'cd': 6, 'de': 0}}},

{'hot': {'109': {'ab': 2.7, 'bc': 24, 'cd': 4, 'de': 5}}},
{'hot': {'109': {'ab': 41, 'bc': 6, 'cd': 12, 'de': 33}}},
{'hot': {'109': {'ab': 32, 'bc': 7, 'cd': 18, 'de': 3.75}}},

{'cold': {'111': {'ab': 25, 'bc': 2, 'cd': 3, 'de': 2.1}}},
{'cold': {'111': {'ab': 5, 'bc': 8, 'cd': 5, 'de': 17}}},
{'cold': {'111': {'ab': -71, 'bc': 42, 'cd': 5, 'de': 16}}},

{'cold': {'110': {'ab': 23, 'bc': 2.4, 'cd': 2.1, 'de': 4.3}}},
{'cold': {'110': {'ab': 11, 'bc': 2.8, 'cd': 4.5, 'de': 2.4}}},
{'cold': {'110': {'ab': 4, 'bc': 5.7, 'cd': 8.7, 'de': 1}}}  ]

代码是这样的:

from collections import defaultdict
counts = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))

for d in data:                   # for the list
    for k1 in d:                 # for the hot-cold level
        for k2 in d[k1]:         # for the 1[0-9]{2} level
            for k3 in d[k1][k2]: # for the [a-z]{2} level
                counts[k1][k2][k3] += d[k1][k2][k3]

print(counts['hot']['111']['ab'])
print(counts['hot']['111']['bc'])

有 2 层 defaultdict 嵌套。

输出:

23.5
-25

关于python - 嵌套字典理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44730125/

相关文章:

python - 使用 groupby 对 Pandas DataFrame 进行计算,然后将其传回到 DataFrame 中?

ios - 从属性构建索引

python - 在 python 字典列表中查找重复项

python - 如何从 python 中的嵌套字典中获取特定键及其值?

c++函数调用函数不起作用

python - 在其他函数中包装 functools.partial 的参数

python - 带有解析html页面的正则表达式python

python - django 管理数据库创建,在 sql 命令被弃用后

python - 使用聚合值、多列解析 CSV 文件

mysql嵌套查询的最大值