2

I want to print a sorted dictionary, which contains a lot of key value pairs (~2000). Each pair consists of a number as the key and a string as the value. It is just about printing, i don't want to sort the dictionary actually.

If i use the sorted() method, python sorts my dictionary, but in an awkward way:

{'0':'foo', '1':'bar', '10': 'foofoo', '100': 'foobar', '1000': 'barbar', 
 '1001': 'barfoo', '1002': 'raboof', ...}

But I want to sort it the 'conventional' way like this:

{'0':'foo', '1':'bar', '2': 'foofoo', '3': 'foobar', '4': 'barbar', 
 '5': 'barfoo', ... , '1001': 'raboof'}

Can I force the method to behave how I want to, or is there another better solution?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
uloco
  • 2,283
  • 4
  • 22
  • 37

3 Answers3

4

Your keys are strings representing integers; if you want a numeric sort, use int() to turn the keys to integers:

sorted(yourdict, key=int)

gives you a numerically sorted list of keys and

sorted(yourdict.items(), key=lambda i: int(i[0]))

gives you items sorted by the numeric value of the key.

However, if you have sequential keys starting at 0, you should be using a list object instead. Index references are faster than dictionary lookups as there is no hashing step required.

Even if your keys do not start at 0 but are still sequential, for a small start index you'd just pad the list with None values:

[None, 'foo', 'bar', 'foofoo', ...]

and index into that starting at 1.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
3

You cannot sort the dictionary, because they are naturally unordered (they use hashing internally), but you can print the key-value pairs in the sorted way

print sorted(d.items(), key = lambda x: int(x[0]))

Output

[('0', 'foo'),
 ('1', 'bar'),
 ('10', 'foofoo'),
 ('100', 'foobar'),
 ('1000', 'barbar'),
 ('1001', 'barfoo'),
 ('1002', 'raboof')]

If you want to iterate through the dictionary in the sorted manner, by default, then you can use the custom SortedDict class from this answer

Also, you can print the dictionary in sorted way, like this

print "{{{}}}".format(", ".join(["{!r}: {!r}".format(key, d[key]) for key in sorted(d, key=int)]))
# {'0': 'foo', '1': 'bar', '10': 'foofoo', '100': 'foobar', '1000': 'barbar', '1001': 'barfoo', '1002': 'raboof'}
Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

You need not use string as keys. You can use integers:

dct = {0:'foo', 1:'bar', 10: 'foofoo', 2: 'foo2'}

If you need strings then add key argument to sorted(). In your case it will be int for converting string int integer:

sorted(dct, key=int)
Michał Niklas
  • 53,067
  • 18
  • 70
  • 114