sort values and return list of keys from dict python

Question:

I have a dictionary like A = {'Name1':34, 'Name2': 12, 'Name6': 46,....}.

How can I get a list of keys sorted by the values, i.e. [Name2, Name1, Name6....]?

Asked By: Alejandro

||

Answers:

Use sorted with the get method as a key (dictionary keys can be accessed by iterating):

sorted(A, key=A.get)
Answered By: phihag

I’d use:

items = dict.items()
items.sort(key=lambda item: (item[1], item[0]))
sorted_keys = [ item[0] for item in items ]

The key argument to sort is a callable that returns the sort key to use. In this case, I’m returning a tuple of (value, key), but you could just return the value (ie, key=lambda item: item[1]) if you’d like.

Answered By: David Wolever

sorted(a.keys(), key=a.get)

This sorts the keys, and for each key, uses a.get to find the value to use as its sort value.

Answered By: Ned Batchelder

Use sorted‘s key argument

sorted(d, key=d.get)
Answered By: Mike Graham
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.