-3

I am trying to sort a dictionary by key.

If I do the following, then the dictionary is sorted like this

1, 20
10, 5
11, 3
2, 30
20, 2

Instead, I wanted to sort it like the following:

1, 20
2, 30
10, 5
11, 3
20, 2

My existing code

writer = csv.writer(open('something.csv', 'wb'))

keylist = count.keys()
keylist.sort()
for key in keylist:
    writer.writerow([key, count[key]])
Michał Trybus
  • 10,996
  • 3
  • 27
  • 41
RKM
  • 3,081
  • 8
  • 35
  • 48

1 Answers1

2

Your dictionary keys are strings, so they are sorted alphabetically. You need to convert the keys to integers first:

keylist = [int(k) for k in count.keys()]
keylist.sort()

for key in keylist:
     writer.writerow([key, count[str(key)]])
poke
  • 339,995
  • 66
  • 523
  • 574
  • `count.keys(key=int)` would be work as the OP does not need ints and you would not have to cast again, you could also just iterate over the dict. – Padraic Cunningham Jun 09 '15 at 20:51