Joseph Joseph - 1 year ago 66
Python Question

How to sort a dictionary having keys as a string of numbers in Python

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 so it looks like:

a = {'1':64,'6':5,'67':7,'88':3, '100':12,'test':34 }

Answer Source

Like everyone else has pointed out, dictionaries have their own ordering and you can't just sort them like you would a list.

One thing I would like to add is that, if you just want to go through the elements of a dictionary in sorted order, that's just:

for k in sorted(a):
    print k, a[k] # or whatever.

If you'd rather have a list comprehension (per Alex):

sortedlist = [(k, a[k]) for k in sorted(a)]

I would like to point out that Alex's use of key=int won't work with your example because one of your keys is 'test'. If you really want he numbers sorted before the non-numerics, you'll have to pass in a cmp function:

def _compare_keys(x, y):
        x = int(x)
    except ValueError:
        xint = False
        xint = True
        y = int(y)
    except ValueError:
        if xint:
            return -1
        return cmp(x.lower(), y.lower())
        # or cmp(x, y) if you want case sensitivity.
        if xint:
            return cmp(x, y)
        return 1

for k in sorted(a, cmp=_compare_keys):
    print k, a[k] # or whatever.

Or maybe you know enough about your keys to write a function to convert them into a string (or other object) that sorts right:

# Won't work for integers with more than this many digits, or negative integers.
def _keyify(x):
        xi = int(x)
    except ValueError:
        return 'S{0}'.format(x)
        return 'I{0:0{1}}'.format(xi, MAX_DIGITS)

for k in sorted(a, key=_keyify):
    print k, a[k] # or whatever.

This would be much faster than using a cmp function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download