Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 264
Ray Avatar asked Sep 10 '08 20:09

Ray


People also ask

Which method returns a sorted list of the dictionary keys?

items() method is used to return the list with all dictionary keys with values. It returns a view object that displays a list of a given dictionary's (key, value) tuple pair. sorted() is used to sort the keys of the dictionary.

Is there a sorted dictionary in Python?

Introduction. We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.


1 Answers

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!

like image 180
dF. Avatar answered Sep 20 '22 16:09

dF.