Retrieving Python dictionary values in order

Complex data in Python may be represented by lists or dictionaries, and sometimes it may be helpful to sort it.

While sorting a list is quite straightforward using


or, if you have a list of lists/tuples and you prefer to sort on a specific value of them:

# sorts using the second value in the element
# example list with name,age,city
l.sort(key=lambda x: x[1])
# l is now sorted by age

Dicationaries are a different thing. Suppose that you have a dictionary mapping students to their grades, like:

grades = { 'Bruce': 100,
           'Diana': 98,
           'Barbara': 78,
           'Clark': 23}

If you print the content of the dictionary it may not appear in sorted order or even using the order in which you specified the keys:

for name in grades:

on my machine I get:

Bruce 100
Clark 23
Diana 98
Barbara 78

If you want to get the list sorted by names, you should first sort the keys:

names = list(grades.keys())
for name in names:

But what about sorting by values? (I.e. sorting by grades instead of names)

By using the previously shown key parameter of the sort method, you can convert the dictionary to a list of tuples, sort it using the second element of the tuple and then you get the result:

#convert dictionary into list
l = [(x,y) for (x,y) in grades.iteritems()]
l.sort(key=lambda x: x[1])

Then iterating through the list you should get:

Clark 23
Barbara 78
Diana 98
Bruce 100


One comment on “Retrieving Python dictionary values in order

  1. […] the fact that old_dict.items() returns a list of dictionary (key,value) elements in an arbitrary order, the last key having a specific value will be the final value in the new_dict. […]

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s