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.
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 :)
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()))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With