3

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']
leba-lev
  • 2,788
  • 10
  • 33
  • 43
  • 1
    What is your desired output? You've demonstrated a sorting of keys is all. Or is it that it's not sorting as you'd like it to? You're getting the text sort not the numeric sort? – g.d.d.c Aug 03 '10 at 22:05
  • Python is just doing what you've told it to do. The way you've called sorted() works on the list of dictionary keys. Since the keys are strings, '15752' appears first ('1' comes before '4' ...). – GreenMatt Aug 03 '10 at 22:08
  • 2
    Don't name your dictionary `dict`. You are shadowing `dict()`. – Felix Kling Aug 03 '10 at 22:10
  • my bad w.r.t. naming the dictionary dict. Thanks for pointing it out! Thanks GreenMatt for your input, I understand now. – leba-lev Aug 03 '10 at 22:12

4 Answers4

10

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.
  • 73,243
  • 15
  • 104
  • 123
3

If they're ALL ints,

sorted(dict, lambda x, y: cmp(int(x), int(y)))
Jason Scheirer
  • 1,668
  • 16
  • 14
2

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
  • 46,865
  • 9
  • 101
  • 111
1

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'}
mmmmmm
  • 32,227
  • 27
  • 88
  • 117