如何在 python 列表的嵌套字典中按键添加值

How to add values in column by key in nested dictionary of list in python

我有列表的嵌套字典。

inputlist= {1: {0: [[1, 20], [6, 20]], 1: [[3, 22], [4, 22]]},
            2: {0: [[2, 21], [7, 21]], 1: [[3, 22], [4, 23]]},
            3: {0: [[5, 23], [8, 22]], 1: [[7, 23], [3, 11]]}}

对于每个键 1,2 和 3,我想对每个键 0 和 1 按列值进行加法。 结果应该是这样的:

{1: {0: [(7, 40)] 1: [(7, 44)]},
 2: {0: [(9, 42)] 1: [(7, 45)]},
 3: {0: [(13, 45)] 1: [(10, 34)]}}

这是我尝试过的:

sum_result={}
for k1, v1 in inputlist.items():
    for (k2,v2) in v1.items():
        sum_result+= v2
    print (sum_result)

你可以试试听写理解

inputlist= {1: {0: [[1, 20], [6, 20]], 1: [[3, 22], [4, 22]]},
            2: {0: [[2, 21], [7, 21]], 1: [[3, 22], [4, 23]]},
            3: {0: [[5, 23], [8, 22]], 1: [[7, 23], [3, 11]]}}

output = {k1:{k2: list(map(sum, zip(*v2))) for k2,v2 in v2.items()} for k1,v2 in inputlist.items()}

# {1: {0: [7, 40], 1: [7, 44]},
#  2: {0: [9, 42], 1: [7, 45]},
#  3: {0: [13, 45], 1: [10, 34]}}

有更简洁的方法可以做到这一点,但我认为如果我们将其分解为逐步方法会更清楚:-

inputlist = {1: {0: [[1, 20], [6, 20]], 1: [[3, 22], [4, 22]]},
             2: {0: [[2, 21], [7, 21]], 1: [[3, 22], [4, 23]]},
             3: {0: [[5, 23], [8, 22]], 1: [[7, 23], [3, 11]]}}
outputlist = {}
for i in inputlist:
    outputlist[i] = {}
    for j in inputlist[i]:
        outputlist[i][j] = []
        ta = [0, 0]
        for k in inputlist[i][j]:
            ta[0] += k[0]
            ta[1] += k[1]
        outputlist[i][j].append(ta)
print(outputlist)

尝试以下代码以获得预期的输出:

inputlist= {1: {0: [[1, 20], [6, 20]], 1: [[3, 22], [4, 22]]},
            2: {0: [[2, 21], [7, 21]], 1: [[3, 22], [4, 23]]},
            3: {0: [[5, 23], [8, 22]], 1: [[7, 23], [3, 11]]}}

sum_result= dict()
for k1, v1 in inputlist.items():
    sum = []
    temp = {}
    for (k2,v2) in v1.items():
        sum = [v2[0][0]+v2[1][0], v2[0][1]+v2[1][1]]
        temp[k2] = sum
    sum_result[k1] = temp

print(sum_result)

输出:

{
   1: {0: [7, 40], 1: [7, 44]}, 
   2: {0: [9, 42], 1: [7, 45]}, 
   3: {0: [13, 45], 1: [10, 34]}
}