I have dict in Python with keys of the following form:
mydict = {\'0\' : 10,
\'1\' : 23,
\'2.0\' : 321,
\'2.1\' : 3
Python's sorting functions can take a custom compare function, so you just need to define a function that compares keys the way you like:
def version_cmp(a, b):
'''These keys just look like version numbers to me....'''
ai = map(int, a.split('.'))
bi = map(int, b.split('.'))
return cmp(ai, bi)
for k in sorted(mydict.keys(), version_cmp):
print k, mydict[k]
In this case you should better to use the key
parameter to sorted()
, though. See Ian Clelland's answer for an example for that.