简体   繁体   中英

How to get a value in a tuple in a dictionary?

I want to access the values in a tuple within a dictionary using a lambda function

I need to get average GPA for each subject by comparing the average grades of the students in that class

I have tried using a lambda but I could not figure it out.


grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}

subjects = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}


def highestAverageOfSubjects(subjects):
    return

The output needs to be ['math','English'] since average GPA of math which is 3.0 is greater then English 2.0 average GPA

You can easily sort everything by using sorted with a key function:

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
result = sorted(subject, key=lambda x: sum(Grade[g] for _, g in subject[x]) / len(subject[x]), reverse=True)
print(result)

Output:

['math','English']

If, as a secondary, you want to sort by the number of students:

result = sorted(subject, key=lambda x: (sum(Grade[g] for _, g in subject[x]) / len(subject[x]), len(subject[x])), reverse=True)
print(result)

One of the issues with the way you have implemented is that you have used a set as values in your subject dict. This means you have to range over each element. But once you have the element, that value would simply be indexed like elem[1] .

For ex:

Grade = {'A': 4.0, 'B': 3.0, 'C': 2.0, 'D': 1.0, 'F' : 0.0}
subject = {'math': {('Jack', 'A'),('Larry', 'C')}, 'English': {('Kevin', 'C'),('Tom','B')}}
for elem in subject['math']:
    print(elem[1])

Output:

C
A

If in the print above you just print(elem) then you'd see something like:

('Larry', 'C')
('Jack', 'A')

So this way you could easily extend your highAveSub(subject) implementation to get what you want.

To find the avg grade of a subject:

def highAveSub(subname):
    total = 0
    for elem in subject[subname]:   #Because your values are of type set, not dict.
        total = total + grade[elem[1]]    #This is how you will cross-reference the numerical value of the grade. You could also simply use enums and I'll leave that to you to find out
    avg = total / len(subject[subname])
    return avg

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM