[英]Iterate through Inner Dictionaries in Python
im a beginner in Python.我是 Python 的初学者。 im practicing a use case to get the final score of the student that are stored in dictionaries.
我正在练习一个用例以获得存储在字典中的学生的最终分数。 COuld you please guide me is there a way to simplify this?
请你指导我有没有办法简化这个?
ScoreCard = {'Antony':{'maths':99,'english':33, 'science':100},'Jeff':{'maths':45,'english':99, 'science':73},
'Mark':{'maths':77,'english':80, 'science':86}}
def sumofMarks(MarkList):
SumMark = 0
for k, v in MarkList.items():
SumMark = SumMark + v
return SumMark
def getMarks(Score, student):
for k,v in Score.items():
if student in Score.keys():
newdic = Score[student]
finalScore = sumofMarks(newdic)
print("Final Score of:", student)
return finalScore
else:
print("Student Not found in registry !")
break
getMarks(ScoreCard,'Jeff')
You can use values()
to get all values of dictionary and sum()
to get sum of them:您可以使用
values()
获取字典的所有值,并使用sum()
获取它们的总和:
ScoreCard = {'Antony': {'maths': 99, 'english': 33, 'science': 100},
'Jeff': {'maths': 45, 'english': 99, 'science': 73},
'Mark': {'maths': 77, 'english': 80, 'science': 86}}
def getMarks(Score, student):
if student in Score:
print(sum(Score[student].values()))
else:
print('Student not found')
getMarks(ScoreCard, 'Jeff')
# 217
ScoreCard = {'Antony':{'maths':99,'english':33, 'science':100},'Jeff':{'maths':45,'english':99, 'science':73},
'Mark':{'maths':77,'english':80, 'science':86}}
name = "Jeff"
if name in ScoreCard.keys():
for k,v in ScoreCard.items():
if k==name:
s = 0
for k1,v1 in v.items():
s+=v1
print("Final Score of :",s)
else:
print(name,"not found in registry")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.