Wednesday, November 23, 2011

Sort a dictionary of dictionaries in Python

Sounds like a big challenge? not at all!

Problem description:
Suppose you have a dictionary of dictionaries. Every key has a dictionary assigned to it, for example:
mydict = {'hello':dict(key1='val10', key2='val20', key3='val30'),
              'world':dict(key1='val11', key2='val21', key3='val31'),
              'howru':dict(key1='val12', key2='val22', key3='val32')}

and your goal is to get a list of mydict "inner" dictionaries, ordered by key2.

A solution for example:
from operator import itemgetter
mydict_values = mydict.values()
mydict_values.sort(key=itemgetter("key2"))

Explained:
mylist.values() gets the list of values from mydict, which is the "inner" dictionaries.
I'm using sort to sort the list of dictionaries, by key, which is looking for item named key2 as the key.

That's all for this time :-)

No comments: