sort values and return list of keys from dict python

PythonDictionary

Python Problem Overview


> Possible Duplicate:
> Python: Sort a dictionary by value

I have a dictionary like this:

A = {'Name1':34, 'Name2': 12, 'Name6': 46,....}

I want a list of keys sorted by the values, i.e. [Name2, Name1, Name6....]

Thanks!!!

Python Solutions


Solution 1 - Python

Solution 2 - Python

Use sorted's key argument

sorted(d, key=d.get)

Solution 3 - Python

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.

Solution 4 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlejandroView Question on Stackoverflow
Solution 1 - PythonphihagView Answer on Stackoverflow
Solution 2 - PythonMike GrahamView Answer on Stackoverflow
Solution 3 - PythonNed BatchelderView Answer on Stackoverflow
Solution 4 - PythonDavid WoleverView Answer on Stackoverflow