Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort dict by key and retrieve value

Given scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}

To get the output [ "bob", "carl", "alex" ]

I can do print([ scores[key] for key in sorted(scores.keys()) ])

Is this the best (most "pythonic") way? I was thinking I could use scores.items() in conjunction with sorted(key=...) to avoid the dictionary lookup, but not sure what that key parameter would be.

like image 446
Frayt Avatar asked Sep 07 '25 17:09

Frayt


2 Answers

Iterating over dict will always use the keys, so you don't have to use the .keys() method.

Also, try not to use space after and before parenthesis.

scores = {0.0: "bob", 5.2: "alex", 2.8: "carl"}
print([scores[key] for key in sorted(scores)])

For more functional approach, you can also use:

scores = {0.0: "bob", 5.2: "alex", 2.8: "carl"}
print(list(map(scores.get, sorted(scores))))

But your solution is perfectly fine :)

like image 181
Yam Mesicka Avatar answered Sep 09 '25 11:09

Yam Mesicka


Another approach would be to create a generator object yielding the values of the dict, cast them to a list and then print it.

print(list(val for val in scores.values()))

like image 22
Stefanos Valoumas Avatar answered Sep 09 '25 11:09

Stefanos Valoumas