views:

48

answers:

4

Hi,

The contents of my dictionary is like so:-

>>> dict
{'6279': '45', '15752': '47', '5231': '30', '475': '40'}

I tried using the sort function on the keys. I noticed that the sort function doesn't work for the key -- 15752. Please find below:-

>>> [k for k in sorted(dict.keys())]
['15752', '475', '5231', '6279']

Could someone point out a way for me to work around this?

Thanks


My expected output is:-

['475', '5231', '6279', '15752']
+2  A: 

If my guess in my comment was right and you want the numeric keys sorted change your line of code to this:

sorted([int(k) for k in test.keys()])
# returns [475, 5231, 6279, 15752]
g.d.d.c
+2  A: 

If they're ALL ints,

sorted(dict, lambda x, y: cmp(int(x), int(y)))
Jason Scheirer
you shouldn't use cmp in this example, use key
hop
+8  A: 

ah you want to sort by the numeric value not the string so you should convert the strings to numbers using int(s) at some point prior or just use sorted(dict.keys(), key=int)

Dan D
+1 for `key=int`
Felix Kling
sorted(dict, key=int) is sufficient
hop
+1  A: 

If you want to sort numerically then store numbers in your dictionary not strings then it will just work

>>> dict
{6279: '45', 15752: '47', 5231: '30', 475: '40'}
Mark