I have a dictionary:
a = {\'100\':12,\'6\':5,\'88\':3,\'test\':34, \'67\':7,\'1\':64 }
I want to sort this dictionary with respect to key s
9 years ago I posted a recipe that starts
Dictionaries can't be sorted -- a mapping has no ordering!
and shows how to get sorted lists out of a dict's keys and values.
With today's Python, and your expressed-plus-implied specs, I'd suggest:
import sys
def asint(s):
try: return int(s), ''
except ValueError: return sys.maxint, s
sortedlist = [(k, a[k]) for k in sorted(a, key=asint)]
the key=asint is what tells sorted to treat those string keys as integers for sorting purposes, so that e.g. '2' sorts between '1' and '12', rather than after them both -- that's what you appear to require, as well as having all non-all-digits keys sort after all
all-digits ones. If you need to also deal with all-digits key strings that express integers larger than sys.maxint, it's a bit trickier, but still doable:
class Infinity(object):
def __cmp__(self, other): return 0 if self is other else 1
infinite = Infinity()
def asint(s):
try: return int(s), ''
except ValueError: return infinite, s
In general, you can get better answers faster if you specify your exact requirements more precisely from the start;-).