How to sort dictionary in Python?1 min read
Can you help me to sort dict in the given order:
d = {1:5,2:6,3:1,4:3,5:23}
now sorted dictionary should be sorted by values such as given below:
d = { 3:1,4:3,1:5,2:6,5:23}
I want to sort the list according to their value retaining its key value.
How can I do this in Python?
Vishal Sharma Answered question
Dictionary cannot be sorted, You can make new sorted list from it in Python.
Here , I have find one useful method to solve this problem:
You can use below method to sort dictionary according to its values in Python.
sorted(d.values())
You can generate the list of sorted (key,value) of given dictionary using given method:
from operator import itemgetter sorted(d.items(), key=itemgetter(1))
store the sorted pair in new list:
from operator import itemgetter e = sorted(d.item() ,key = itemgetter(1)) print(e)
Output:
[(3,1),(4,3),(1,5),(2,6),(5,23)]
This solution has solved my problem.
Vishal Sharma Answered question