In Python, how do I iterate over a dictionary in sorted key order?
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Techno Intrigue Looping
--
Chapters
00:00 In Python, How Do I Iterate Over A Dictionary In Sorted Key Order?
00:23 Accepted Answer Score 184
00:58 Answer 2 Score 85
01:10 Answer 3 Score 44
01:51 Answer 4 Score 36
02:05 Answer 5 Score 6
02:34 Thank you
--
Full question
https://stackoverflow.com/questions/3645...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #sorting #dictionary
#avk47
ACCEPTED ANSWER
Score 184
Haven't tested this very extensively, but works in Python 2.5.2.
>>> d = {"x":2, "h":15, "a":2222}
>>> it = iter(sorted(d.iteritems()))
>>> it.next()
('a', 2222)
>>> it.next()
('h', 15)
>>> it.next()
('x', 2)
>>>
If you are used to doing for key, value in d.iteritems(): ... instead of iterators, this will still work with the solution above
>>> d = {"x":2, "h":15, "a":2222}
>>> for key, value in sorted(d.iteritems()):
>>>     print(key, value)
('a', 2222)
('h', 15)
('x', 2)
>>>
With Python 3.x, use d.items() instead of d.iteritems() to return an iterator.
ANSWER 2
Score 85
Use the sorted() function:
return sorted(dict.iteritems())
If you want an actual iterator over the sorted results, since sorted() returns a list, use:
return iter(sorted(dict.iteritems()))
ANSWER 3
Score 44
A dict's keys are stored in a hashtable so that is their 'natural order', i.e. psuedo-random. Any other ordering is a concept of the consumer of the dict.
sorted() always returns a list, not a dict. If you pass it a dict.items() (which produces a list of tuples), it will return a list of tuples [(k1,v1), (k2,v2), ...] which can be used in a loop in a way very much like a dict, but it is not in anyway a dict!
foo = {
    'a':    1,
    'b':    2,
    'c':    3,
    }
print foo
>>> {'a': 1, 'c': 3, 'b': 2}
print foo.items()
>>> [('a', 1), ('c', 3), ('b', 2)]
print sorted(foo.items())
>>> [('a', 1), ('b', 2), ('c', 3)]
The following feels like a dict in a loop, but it's not, it's a list of tuples being unpacked into k,v:
for k,v in sorted(foo.items()):
    print k, v
Roughly equivalent to:
for k in sorted(foo.keys()):
    print k, foo[k]
ANSWER 4
Score 36
Greg's answer is right. Note that in Python 3.0 you'll have to do
sorted(dict.items())
as iteritems will be gone.