I've been trying for several hours to go through a dictionary and get three highest-value keys to be presented in the output.
So here's an example dictionary:
dict1 = {
"a": 5,
"b": 1,
"c": 20,
"d": 15,
"e": 100,
"f": 75
}
And I want to parse out the three highest values and present them something like this:
'e' has a value of 100
'f' has a value of 75
'c' has a value of 20
So it should be key-value pairs, not just the values.
I tried something like this but it didn't seem convenient at all.
v = list(dict1.values())
k = list(dict1.keys())
print(f"{k[v.index(max(v))]} has a value of {max(v)}.")
# and so forth. not to mention this is only the one highest value, I need three
I'm sure there's a really simple way right under my nose. Thank you.
CodePudding user response:
The standard library Counter
class can make short work of what you are trying to do:
from collections import Counter
dict1 = {
"a": 5,
"b": 1,
"c": 20,
"d": 15,
"e": 100,
"f": 75
}
for k, v in Counter(dict1).most_common(3):
print(f"{k} has a value of {v}")
Output:
e has a value of 100
f has a value of 75
c has a value of 20
CodePudding user response:
Try to sort the dictionary items and print first 3 items:
dict1 = {"a": 5, "b": 1, "c": 20, "d": 15, "e": 100, "f": 75}
for k, v in sorted(dict1.items(), key=lambda k: k[1], reverse=True)[:3]:
print(f"'{k}' has a value of {v}")
Prints:
'e' has a value of 100
'f' has a value of 75
'c' has a value of 20