Jan-17-2021, 09:08 AM
Hello everyone. Hope you are all having a great time.
Here's a simple question:
There's a dictionary, and I want to extract the top 3 students from it.
I have successfully achieved the goal and the code is pretty much readable (I suppose), but I'm sure there's a more concise way of achieving the same output (using less lines of code).
Here's a simple question:
There's a dictionary, and I want to extract the top 3 students from it.
I have successfully achieved the goal and the code is pretty much readable (I suppose), but I'm sure there's a more concise way of achieving the same output (using less lines of code).
scores = {'Josh': 90, 'Adam': 72, 'Amin': 81, 'Narnia': 56, 'Natalie': 65, 'David': 68, 'Karen': 92, 'Elsa': 75} names = list(scores.keys()) values = list(scores.values()) values.sort() x = 1 for i in values: while x < 4: print(f"Top {x}:", names[-x] ,values[-x]) x += 1
Output:Top 1: Elsa 92
Top 2: Karen 90
Top 3: David 81
Thank you all in advance.