How to sort a Python dictionary by value?
python, sorting
Solution
Dictionaries can't be sorted as such, but you can sort their contents:
sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2)
sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
You can put the results into a `collections.OrderedDict` (since 2.7):
OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
OrderedDict(sorted(a_dict.items(), key=lambda item: item[1][1]) # Python 3
Problem
Possible Duplicate: In Python how do I sort a list of dictionaries by values of the dictionary? Sorting Python dictionary based on nested dictionary values I have dictionary of the form as mentioned below: ``` a_dict = { 'e': (1, 100), 'a': (2, 3) } ``` I am unable to sort it by the second element of the tuple. The resultant dictionary will appear as below: ``` a_dict = { 'a': (2, 3), 'e': (1, 100) } ```
Related problems
- How do I sort a dictionary by value?
- Sorting Python dictionary based on nested dictionary values
- How to sort a list of dictionaries by a value of the dictionary in Python?
- Sorting Python dictionary based on nested dictionary values
- How to sort a list of dictionaries by a value of the dictionary in Python?