Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of dictionary elements ordered by dictionary key

Tags:

python

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?

like image 869
Randomblue Avatar asked Nov 19 '25 02:11

Randomblue


2 Answers

Sort before iterating.

for key in sorted(d):
like image 54
Ignacio Vazquez-Abrams Avatar answered Nov 20 '25 18:11

Ignacio Vazquez-Abrams


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

for key in sorted(d):
   print(d[key])
like image 21
Sven Marnach Avatar answered Nov 20 '25 16:11

Sven Marnach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!