你好,我是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)对此有任何解决方案,谢谢。
发布于 2020-03-21 02:10:39
>>> {key: max(value.values()) for key, value in gradebooks.items()}
{'business analytics': 95, 'Python programming': 100, 'R programming': 100}发布于 2020-03-21 02:14:14
您可以尝试执行以下操作来获取每个类别的最大值:
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如果这有帮助,请告诉我!
https://stackoverflow.com/questions/60779469
复制相似问题