📜  Python – 嵌套记录值求和

📅  最后修改于: 2022-05-13 01:55:44.149000             🧑  作者: Mango

Python – 嵌套记录值求和

有时,在处理记录时,我们可能会遇到需要对键的嵌套键进行求和并将总和记录为键的值的问题。这可以在数据科学和网络开发等领域有可能的应用。让我们讨论可以执行此任务的某些方式。

方法#1:使用循环
这是我们可以执行此任务的蛮力方式。在此,我们遍历嵌套字典,总结值并分配给相应的键。

# Python3 code to demonstrate working of 
# Nested record values summation
# Using loop
  
# initializing dictionary
test_dict = {'gfg' : {'a' : 4, 'b' : 5, 'c' : 6},
             'is' : {'a': 2, 'b' : 9, 'c' : 10},
             'best' : {'a' : 10, 'b' : 2, 'c' : 12}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Nested record values summation
# Using loop
res = dict()
for sub in test_dict:
    sum = 0
    for keys in test_dict[sub]:
        sum = sum + test_dict[sub][keys]
    res[sub] = sum
      
# printing result 
print("The dictionary after keys summation is : " + str(res)) 
输出 :
The original dictionary is : {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
The dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}

方法 #2:使用sum()
这是可以执行此任务的另一种方式。在此,我们使用 sum() 执行计算任务。

# Python3 code to demonstrate working of 
# Nested record values summation
# Using sum()
from collections import Counter
  
# initializing dictionary
test_dict = {'gfg' : {'a' : 4, 'b' : 5, 'c' : 6},
             'is' : {'a': 2, 'b' : 9, 'c' : 10},
             'best' : {'a' : 10, 'b' : 2, 'c' : 12}}
  
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
  
# Nested record values summation
# Using sum()
res = dict()
for sub in test_dict:
    res[sub] = sum([test_dict[sub][ele] for ele in test_dict[sub]])
  
# printing result 
print("The dictionary after keys summation is : " + str(dict(res))) 
输出 :
The original dictionary is : {'best': {'a': 10, 'c': 12, 'b': 2}, 'is': {'a': 2, 'c': 10, 'b': 9}, 'gfg': {'a': 4, 'c': 6, 'b': 5}}
The dictionary after keys summation is : {'best': 24, 'is': 21, 'gfg': 15}