I was trying to sort a dictionary by keys but whenever I printed it back, it returned indexes in random order.
students = {'John' : 23, 'Harry' :20, 'Adam' : 25}
I have a dictionary like this. I want to sort it using keys in ascending order i.e. I want the output as:
{'Adam' :25,'Harry' :20,'John' :23}
Here's what I tried to solve this.
I used sorted(students.items()) But it returned the randomly sorted dictionary.
I tried
sorted(students.items(), key=lambda x:x[0])
But, this also didn't work.
- I also tried collections.OrderedDict
import collections
sortedstudents =collections.OrderedDict(students.items())
This actually sorted the list but the output was not a Python dictionary. It was like :
{('Adam', 25),('Harry',20),('John',23)}
But, I want output like this :
{'Adam' :25,'Harry' :20,'John' :23}
Can anybody please help me solve this?
Thanks in advance!