user2574761 - 1 month ago 7
Python Question

# How to order numeric dictionary keys with 2 digits

I have a dictionary in python like the one below, containing about 20 keys:

``````a = { "1": "","2":"","3":""........"20":"" }
``````

To sort the dictionary I'm doing the following:

`````` for key in sorted(a.iterkeys()):
print key
``````

However it doesn't seem to keep the keys in order. It will result in this output:

1 11 12 13 14 15 16 17 18 19 2 20 3 4 5 6 7 .....

I was looking for something like:

1 2 3 4 5 6 ....

Any help would be apreciated

I'm assuming your real dictionary looks like this:

``````a = {"1": "", "2": "", …, "20": ""}
``````

Otherwise, you wouldn't have had this problem in the first place.

If that's the problem, the answer is this:

``````for key in sorted(a.iterkeys(), key=int):
print key
``````

The trick here is that `key` argument. You can pass any function you want as a `key` to `sorted` (and most other sorting-related functions), and it will call that function on all of the values and sort based on the result of that function, instead of on the actual values.

The builtin `int` function takes any argument and (if possible) converts it to an integer. In particular, if you give it the string `"3"` it'll give you the number `3`, and if you give it `"20"`, it'll give you `20`. And, while `"3" > "20"` (because strings are compared alphabetically), `3 < 20` (because numbers are compared numerically).

See the Sorting HOWTO in the docs for further details.