0

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.

  1. I used sorted(students.items()) But it returned the randomly sorted dictionary.

  2. I tried

    sorted(students.items(), key=lambda x:x[0])

But, this also didn't work.

  1. 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!

Sumit
  • 31
  • 2
  • In general if you find yourself wanting to sort a dictionary (as opposed to operating on sorted elements from a dictionary) then you need to reconsider using a dictionary. Why do you need to sort it? If it's just for printing then you can iterate on `sorted(students.items())` and print the elements that way, no sorting of the actual dictionary required. – Kemp Apr 01 '21 at 10:21
  • 1
    Dictionaries, conceptually, do not have an order. – Karl Knechtel Apr 01 '21 at 10:28

1 Answers1

0

Try this:

students = {'John' : 23, 'Harry' :20, 'Adam' : 25}
    
sorted_students = dict(sorted(students.items()))
print(sorted_students)
AkshayJ
  • 321
  • 1
  • 7