在嵌套字典中添加不同级别的值

时间:2017-08-10 21:00:11

标签: python dictionary sum

我有一个散列值表。这是它的样子

hash_of_errors =
    {
      'i0': 
         {
            200: 
                 {
                   0: 12,
                   1: 23
                 },
            300: 
                 {
                   0: 4,
                   1: 3
                 }
            },
        'i1': 
         {
            100: 
                 {
                   0: 2,
                   1: 23
                 },
            300: 
                 {
                   0: 4,
                   1: 3
                 }
            }
    }

所以它是

的哈希
  • 第一级:单位名称i0,i1,i2等
  • 第二级:计数:200,300,400等。
  • 第三级:等级:0,1等。
  • 和值是错误数。

我想要做的是创建一个二维数组,第一个索引是每个单位,第二个索引是每个计数的错误总数(级别0,1的所有错误的总和)。在这种情况下,我会得到这个。

[[0, 35, 7], #i0 unit: 37 (12+23) for count 200, 7 for 300 and 0s for 100
 [24, 0, 7]] #i1 unit: 24 for count 100, 7 for 300 and 0s for 200

第二个2d数组/列表我需要打印第一个索引是每个级别(跨越所有i0,i1),第二个索引是每个计数的错误总数

[[2, 12, 8] #0 level: at count 100 we have 2, at 300 we have 8(4+4)
 [23, 23, 7]] #1 level: at count of 100 we have 23, at 300 we have 7(4+3)

我如何在python中执行此操作?

1 个答案:

答案 0 :(得分:1)

你基本上可以通过一些理解来完成所有这些工作。第一个是:

>>> units = ['i0', 'i1']
>>> counts = [100, 200, 300]
>>> levels = [0, 1]

>>> [[sum(hash_of_errors[unit].get(count, {}).values()) for count in counts] for unit in units]
[[0, 35, 7], [25, 0, 7]]

第二个更复杂,因为你需要遍历所有这些:

>>> [[sum(hash_of_errors[unit].get(count, {}).get(level, 0) for unit in units) for count in counts] for level in levels]
[[2, 12, 8], [23, 23, 6]]

请注意,您也可以使用手动迭代而不是理解。他们不会成为单行,但也许更容易理解。

例如:

# To translate name to position
units = {'i0': 0, 'i1': 1}
counts = {100: 0, 200: 1, 300: 2}
levels = {0: 0, 1: 1}

res = [[0, 0, 0], [0, 0, 0]]  # basic result, we will modify these values as we go along
for unit, unitdict in hash_of_errors.items():
    for count, countdict in unitdict.items():
        for level, errorcount in countdict.items():
            res[units[unit]][counts[count]] += errorcount
>>> res
[[0, 35, 7], [25, 0, 7]]

或在第二种情况下:

res = [[0, 0, 0], [0, 0, 0]]
for unit, unitdict in hash_of_errors.items():
    for count, countdict in unitdict.items():
        for level, errorcount in countdict.items():
            res[levels[level]][counts[count]] += errorcount
>>> res
[[2, 12, 8], [23, 23, 6]]
相关问题