Frayt
Frayt

Reputation: 1233

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.

Upvotes: 4

Views: 1760

Answers (5)

Hariharan Ragothaman
Hariharan Ragothaman

Reputation: 582

To sort dictionary by their keys and retrieve their values:

# This is your initial dictionary
scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}

# This sorts your dictionary by it's keys as mentioned by x[0]
sorted_scores = {k:v for k, v in sorted(scores.items(), key=lambda x:x[0])}

# Now we are getting all the values in the sorted order and storing it in result
result = list(sorted_scores.values())

# Now, result will be:
['bob', 'carl', 'alex']

# Also sorted_scores will be:
{0.0: 'bob', 2.8: 'carl', 5.2: 'alex'}

Upvotes: 0

Willie Cheng
Willie Cheng

Reputation: 8263

Please try this code below the code content, it will be sort dict by key.

scores = { 0.0: "bob", 5.2: "alex", 2.8: "carl"}
for key, value in sorted(scores.items(), key=lambda kv: kv[0], reverse=True):
    print("%s: %s" % (key, value))

5.2: alex
2.8: carl
0.0: bob

Upvotes: 0

Stefanos Valoumas
Stefanos Valoumas

Reputation: 36

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()))

Upvotes: 1

Yam Mesicka
Yam Mesicka

Reputation: 6601

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 :)

Upvotes: 2

sam46
sam46

Reputation: 1271

if you insist on using .items(), the key argument is key=lambda t: t[0], but in this case key=lambda t: t works the same (but breaks ties by the value). t is used as key by default so you don't need to specify one:

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

outputs:

[(0.0, 'bob'), (2.8, 'carl'), (5.2, 'alex')]

now to get a list of values you can "unzip" like this:

print(
    list(list(zip(*sorted(scores.items())))[1])
)

Upvotes: 0

Related Questions