Can I sort text by its numeric value in Python?

You can sort the keys the way that you want, by splitting them on ‘.’ and then converting each of the components into an integer, like this:

sorted(mydict.keys(), key=lambda a:map(int,a.split('.')))

which returns this:

['0',
 '1',
 '2.0',
 '2.1',
 '3',
 '4.0.0',
 '4.0.1',
 '5',
 '10',
 '11.0',
 '11.1',
 '12.0',
 '12.1.0',
 '12.1.1']

You can iterate over that list of keys, and pull the values out of your dictionary as needed.

You could also sort the result of mydict.items(), very similarly:

sorted(mydict.items(), key=lambda a:map(int,a[0].split('.')))

This gives you a sorted list of (key, value) pairs, like this:

[('0', 10),
 ('1', 23),
 ('2.0', 321),
 ('2.1', 3231),
 ('3', 3),
 # ...
 ('12.1.1', 2)]

Leave a Comment