In Python, how can you easily retrieve sorted items from a dictionary?


Dictionaries unlike lists are not ordered (and do not have the 'sort' attribute). Therefore, you can not rely on getting the items in the same order when first added.

What is the easiest way to loop through a dictionary containing strings as the key value and retrieving them in ascending order by key?

For example, you had this:

d = {'b' : 'this is b', 'a': 'this is a' , 'c' : 'this is c'}

I want to print the associated values in the following sequence sorted by key:

this is a
this is b
this is c
By : Ray Vega


You can also sort a dictionary by value and control the sort order:

import operator

d = {'b' : 'this is 3', 'a': 'this is 2' , 'c' : 'this is 1'}

for key, value in sorted(d.iteritems(), key=operator.itemgetter(1), reverse=True):
    print key, " ", value

b this is 3
a this is 2
c this is 1

By : Cookey

Do you mean that you need the values sorted by the value of the key? In that case, this should do it:

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

EDIT: changed to use sorted(d) instead of sorted(d.keys()), thanks Eli!

By : dF.

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

This video can help you solving your question :)
By: admin