Home > Software design >  find out sum of values in nested dictionary and return the largest key
find out sum of values in nested dictionary and return the largest key

Time:02-02

my_dict = {"student1": {"subject1": 100,"subject2":80, "subject3": 70},
           "student2": {"subject1": 500,"subject2":30, "subject3": 600}}

need to find out which student has highest sum of marks?

CodePudding user response:

You can use a dictionary comprehension to get the sum of scores for each student. Then, you can use max() to find the student with the highest total score:

data = {"student1": {"subject1": 100,"subject2":80, "subject3": 70},
           "student2": {"subject1": 500,"subject2":30, "subject3": 600}}

totals = {student_id: sum(scores.values()) for student_id, scores in data.items()}
print(totals) # Prints {'student1': 250, 'student2': 1130}.

# Each element in .items() is a tuple with the student id as the first element,
# and their score as the second element.
# The key argument has us find the tuple with the maximum score.
top_scorer, top_score = max(totals.items(), key=lambda x: x[1])
print(top_scorer) # Prints student2.
print(top_score) # Prints 1130.

CodePudding user response:

Calculate highest score for both students as follows:

x = [sum(my_dict[i].values()) for i in my_dict.keys()]

then print the name of the student with the highest marks as follows:

if x[0] > x[1]:
    print("Student 1 has highest marks: ", x[0])
else:
    print("Student 2 has highest marks: ", x[1])

CodePudding user response:

Just do:

max(my_dict, key=lambda x:sum(my_dict[x][i] for i in my_dict[x]))


'student2'

CodePudding user response:

If you're going to be working a lot with the data, it's probably best to convert it to a more useful data type, e.g.

df= pd.DataFrame.from_dict(my_dict, orient = 'index')

then you can do

df.sum(axis=1).sort_values(ascending = False).index[0]

or

sums = df.sum(axis=1)
max(sums.index, key = lambda x: sums[x])
  •  Tags:  
  • Related