Home python Sort dictionary keys in ascending order

Sort dictionary keys in ascending order

Author

Date

Category

Hello.

Given a dictionary

{'2.3': ['0', '1'], '4.9': ['0', '1'], '4.7': ['0', '1'], '3.5': ['0', '1'], '2.4': ['0', '1'], '3.17' : ['0', '1'], '4.8': ['0', '1'], '3.6': ['0']}

It is necessary to sort it by keys in ascending order. I’m trying to do this:

for x in sorted (dict_list.keys (), key = lambda x: float (x [: len (x )-1])):
  print (x)

It turns out

2.3, 2.4, 3.5, 3.6, 3.17, 4.9, 4.7, 4.8

In general, it clearly sorts something wrong. Can you please tell me how to sort in ascending order of keys? Thanks in advance.


Answer 1, authority 100%

If you want to return a sorted list of keys / values, you can simply sort the dictionary by its keys:

for k in sorted (dict_list.keys ()):
  print (k, ':', dict_list [k])

If you need to store sorted key / value pairs, try using OrderedDict

from collections import OrderedDict
# sort in ascending order of dictionary keys
OrderedDict (sorted (dict_list.items (), key = lambda t: t [0]))

OrderedDict Documentation

UPD
at the request of the author, sorting in ascending order with the condition that 3.17 should be the last

for i in sorted (dict_list.items (), key = lambda x: (len (x [0]) , x [0])):
  print (i [0])

If 3.17 should come first, you can simply add - to the condition:

.. lambda x: (-len (x [0]), x [0]))

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions