Reputation: 116433
I have a dictionary d
for which the keys are all strings. Now when I do:
for key in d:
print(d[key])
I get the elements of d
is some "random" order. How can I force the element of d
to come out sorted by the lexicographical order?
Upvotes: 2
Views: 2384
Reputation: 16338
Additionaly to those answers, if your dictionary is immutable but have significant amount of items and need to be read more often than once, it might be useful to repack items using the collections.OrderedDict container.
Upvotes: 1
Reputation: 602715
Use sorted()
to sort any iterable, including a dictionary:
for key in sorted(d):
print(d[key])
Upvotes: 8