[英]How can I update the values of a list of dictionaries
我想將每個字典中每個鍵的值與每個列表中的值相加。
D = [{1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1:
10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2:
10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3:
10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}]
C = [[1, 2, 1], [1, 2, 1], [2, 1, 1], [3, 1, 1], [1, 1, 2], [1, 1, 2], [1, 2, 2], [1, 1, 1], [1, 2,
2], [1, 1, 3], [2, 1, 2], [2, 1, 2], [2, 2, 1], [2, 2, 1], [2, 1, 1], [1, 3, 1]]
for c in C:
for cdx in range(0, len(c)):
key = cdx + 1
value = c[cdx]
for d in D:
cu_val = d.get(key)
up_val = cu_val + value
d[key] = up_val
print(D)
字典列表和列表列表的長度相等。 我想通過將它的值添加到相同對應的 position 中列表的值來更新字典嗎?
解決方案:
這應該可以解決您的目的:)
D = [{1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1:
10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2:
10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3:
10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}, {1: 10, 2: 10, 3: 10}]
C = [[1, 2, 1], [1, 2, 1], [2, 1, 1], [3, 1, 1], [1, 1, 2], [1, 1, 2], [1, 2, 2], [1, 1, 1], [1, 2,
2], [1, 1, 3], [2, 1, 2], [2, 1, 2], [2, 2, 1], [2, 2, 1], [2, 1, 1], [1, 3, 1]]
for d, c in zip(D, C):
for key, val in d.items():
d[key] = val + c.pop()
print(D)
Output:
[{1: 11, 2: 12, 3: 11}, {1: 11, 2: 12, 3: 11}, {1: 11, 2: 11, 3: 12}, {1: 11, 2: 11, 3: 13}, {1: 12, 2: 11, 3: 11}, {1: 12, 2: 11, 3: 11}, {1: 12, 2: 12, 3: 11}, {1: 11, 2: 11, 3: 11}, {1: 12, 2: 12, 3: 11}, {1: 13, 2: 11, 3: 11}, {1: 12, 2: 11, 3: 12}, {1: 12, 2: 11, 3: 12}, {1: 11, 2: 12, 3: 12}, {1: 11, 2: 12, 3: 12}, {1: 11, 2: 11, 3: 12}, {1: 11, 2: 13, 3: 11}]
根據我對你的問題的理解,下面的代碼應該可以做到:
for c, d in zip(C, D):
for idx, val in enumerate(c):
d[idx+1] += val
print(D)
有用。
l1 = len(D) #number of dictionary
l2 = len(D[0]) # number of element of dictionary
for i in range(l1):
for j in range(l2):
D[i][j+1] += C[i][j]
print(D)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.