Randomblue
Randomblue

Reputation: 116433

Get list of dictionary elements ordered by dictionary key

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

Answers (3)

Odomontois
Odomontois

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

Sven Marnach
Sven Marnach

Reputation: 602715

Use sorted() to sort any iterable, including a dictionary:

for key in sorted(d):
   print(d[key])

Upvotes: 8

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799520

Sort before iterating.

for key in sorted(d):

Upvotes: 14

Related Questions