-1

Python At the moment my code prints this

Jem - 8
Rob - 9
Liah - 9
Zambia - 3

(name and score) But how would I get this ordered highest to lowest? I researched and read something about Lambda but I am not too sure how it works? I have a lot of code, by here is the sorting lines

for name in name_scores: #16
      print(name, '-', max(name_scores[name]))#17 

It prints the highest score, which I would now like to sort.

Romano Zumbé
  • 7,893
  • 4
  • 33
  • 55
M.Weiss
  • 79
  • 2
  • 13

2 Answers2

1

I'm assuming your name_scores is a dict with keys being names, and values being a list of all their scores.

With this in mind, you can iterate over the sorted dict like so:

for name in sorted(name_scores, key=lambda x: max(name_scores[x]), reverse=True):
    print(name, '-', max(name_scores[name]))

sorted() takes an argument key which allows you to specify how you want the object sorted. If you don't specify a key for a dict, then the sort will apply to the keys (which doesn't help us here).

So instead we can use the key to tell sorted what we want to sort by. A little magic is needed here in the form of a lambda.

sorted() iterates through your dict and one by one it calls the lambda to obtain a value. The lambda's first argument (x) is supplied automatically and is a reference to the name at the time the lambda is called. So the first time through it looks like this:

lambda x='Jem': max(name_scores[x])

This repeats for each name in your dict and those values retrieved are then used for the sort.

MrAlexBailey
  • 5,219
  • 19
  • 30
0

If name_scores is a dict with names as keys and lists of scores as values such as:

name_scores = {'Jem':[8,4,5],'Rob':[9,1,5], 'Liah':[9], 'Zambia':[3]}

Then you can can get your required output by doing the following:

for name, scores in sorted(name_scores.items(),key=lambda x: max(x[1]), reverse=True):
    print(name,'-',max(scores))

How it works:

name_scores.items() produces a list of (name, scores) tuples.

lambda is used to define a function which returns the maximum score for each tuple.

Using sorted on a sequence with the key option will pass each item in the sequence to a function and sort by the value returned by the function. In this case we use sorted using the lambda function as a key.

If you are having trouble understanding the use of lambda functions it is often helpful to consider the following equivalent code without lambda functions:

def max_score(x):
    return max(x[1])

name_scores = {'Jem':[8,4,5],'Rob':[9,1,5], 'Liah':[9], 'Zambia':[3]}
for name, scores in sorted(name_scores.items(), key=max_score, reverse=True):
    print(name,'-',max(scores))
Dan S
  • 1
  • 2