[英]Sum of items in nested python dictionary
I have a nested dictionary我有一个嵌套字典
mydict = {
'school1': {
'grades1': [78, 96, 80],
'grades2' : [81, 86, 90]},
'school2': {
'grades3' : [60, 65, 70],
'grades4' : [67, 98, 100]}
}
I want to find the sums of 'grade' sub dictionary I have and can't quite figure it out.我想找到我拥有的“等级”子词典的总和,但不太明白。 I do not want to hard code我不想硬编码
sum(mydict['school1']['grades1'])
and so on.等等。
'for schools in my_dict2: '对于 my_dict2 中的学校:
print(schools)
for grades in my_dict2[schools]:
print(grades)
for values in my_dict2[schools][grades]:
print(sum(values))`
I got to the values, but trying to take the sum of values here results in TypeError: 'float' object is not iterable我得到了这些值,但是尝试在此处计算值的总和会导致 TypeError: 'float' object is not iterable
Any help much appreciated!非常感谢任何帮助! Thanks!谢谢!
Easiest way to loop through dictionaries in python is to use dict.values()
, dict.keys()
, or its combined cousin dict.items()
.在 python 中遍历字典的最简单方法是使用 dict.values dict.values()
、 dict.keys()
或其组合表亲dict.items()
。 So a purely for-loop
implementation might look like so:所以一个纯粹for-loop
实现可能看起来像这样:
sumGrades = []
for school in mydict.values():
sumGrades.append(0)
for grade in school.values():
sumGrades[-1] += sum(grade)
And converting to list comprehension:并转换为列表理解:
sumGrades = [sum(sum(g) for g in s.values()) for s in mydict.values()]
I have a nested dictionary我有一个嵌套字典
mydict = {
'school1': {
'grades1': [78, 96, 80],
'grades2' : [81, 86, 90]},
'school2': {
'grades3' : [60, 65, 70],
'grades4' : [67, 98, 100]}
}
I want to find the sums of 'grade' sub dictionary I have and can't quite figure it out.我想找到我拥有的“等级”子词典的总和,但无法弄清楚。 I do not want to hard code我不想硬编码
sum(mydict['school1']['grades1'])
and so on.等等。
'for schools in my_dict2: '对于 my_dict2 中的学校:
print(schools)
for grades in my_dict2[schools]:
print(grades)
for values in my_dict2[schools][grades]:
print(sum(values))`
I got to the values, but trying to take the sum of values here results in TypeError: 'float' object is not iterable我得到了这些值,但试图在这里取值的总和会导致 TypeError: 'float' object is not iterable
Any help much appreciated!非常感谢任何帮助! Thanks!谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.