-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
  • 11,526
  • 3
  • 30
  • 42
RKM
  • 3,151
  • 9
  • 37
  • 50

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
  • 369,085
  • 72
  • 557
  • 602
  • `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