Showing posts with label sorted. Show all posts
Showing posts with label sorted. Show all posts

2013-04-05

Small Python tip - sorted iterating over dictionary

Python dictionaries are great. However, iterating over dictionaries results in an unsorted order:
In [1]: d = {'a':10, 'b': 20, 'c': 30}

In [2]: for key,value in d.iteritems():
   ...:     print key, value
   ...:
a 10
c 30
b 20
The fix is to use sorted():

In [3]: for key,value in sorted(d.iteritems()):
   ...:     print value
   ...:
a 10
b 20
c 30