[英]Python - Finding max value in nested dictionary
您好,我是 Python 新手,在從嵌套字典生成最大值時遇到了一些問題。
原始字典:
gradebooks = {'business analytics': {'Alice': 95, 'Troy': 92}, 'Python programming': {'James': 89, 'Charles': 100, 'Bryn': 69, 'Alice': 100}, 'R programming': {'Troy': 93, 'James': 100, 'Charles': 88}}
我要生成的新字典:
{'business analytics': 95, 'Python programming': 100, 'R programming': 100}
我使用了以下代碼但無法生成最大值:
ISOM_gradebooks = {course: v for course, name in gradebooks.items() for key, v in name.items()}
print(ISOM_gradebooks)
有什么解決辦法,謝謝。
>>> {key: max(value.values()) for key, value in gradebooks.items()}
{'business analytics': 95, 'Python programming': 100, 'R programming': 100}
你可以試試這個來獲得每個類別的最大值:
outputDict = {}
# This will loop on each key and value of your gradebooks dictionary
for k,v in gradebooks.items()
maxVal = 0
# This will loop over the grades of each student
for grade in v.values():
if grade > maxVal:
maxVal = grade
# Update your dictionary with the value of the maxVal of your subject k
outputDict[k] = maxVal
讓我知道這是否有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.