I have dict in Python with keys of the following form:
mydict = {'0' : 10,
'1' : 23,
'2.0' : 321,
'2.1' : 3231,
'3' : 3,
'4.0.0' : 1,
'4.0.1' : 10,
'5' : 11,
# ... etc
'10' : 32,
'11.0' : 3,
'11.1' : 243,
'12.0' : 3,
'12.1.0': 1,
'12.1.1': 2,
}
Some of the indices have no sub-values, some have one level of sub-values and some have two. If I only had one sub-level I could treat them all as numbers and sort numerically. The second sub-level forces me to handle them all as strings. However, if I sort them like strings I’ll have 10 following 1 and 20 following 2.
How can I sort the indices correctly?
Note: What I really want to do is print out the dict sorted by index. If there’s a better way to do it than sorting it somehow that’s fine with me.
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:
which returns this:
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:
This gives you a sorted list of (key, value) pairs, like this: