sort values and return list of keys from dict python
PythonDictionaryPython 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
Use http://docs.python.org/library/functions.html#sorted">`sorted`</a> with the http://docs.python.org/library/stdtypes.html#dict.get">`get`</a> method as a key (dictionary keys can be accessed by http://docs.python.org/library/stdtypes.html#dict">iterating</a>;):
sorted(A, key=A.get)
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.