[Tutor] Sorting Dictionary of Dictionary by certain Value

Kent Johnson kent37 at tds.net
Wed Sep 24 04:18:30 CEST 2008


On Tue, Sep 23, 2008 at 8:41 PM, Joe Python <jopython at gmail.com> wrote:
> Hi Pythonistas,
>
> I have a large dictionary of dictionary (50,000+ keys) which has a structure
> as follows:
> DoD = {
>         'flintstones' : {
>         'husband'   : "fred",
>         'pal'       : "barney",
>         'income'    :  500,
>     },
>     'jetsons' : {
>         'husband'   : "george",
>         'wife'      : "jane",
>         'his boy' : "elroy",
>         'income'    :  700,
>     },
>     'simpsons' : {
>         'husband'   : "homer",
>         'wife'      : "marge",
>         'kid'       : "bart",
>         'income'    :  600,
>     },
> };
>
> I want to sort the dictionary by 'income'
> Is there an efficient way to do the same.

As has been pointed out, you can't sort a dictionary, it is unordered.
You can sort the list of key, value pairs. The simplest way is to make
a key function that extracts the value on which to sort.

The key, value pairs will look like ('flintstones', {
        'husband'   : "fred",
        'pal'       : "barney",
        'income'    :  500,
    )

You want to sort on the 'income' element of the value; this key
function will work:
def key(item):
  return item[1]['income']

Then sort with
sorted(DoD.iteritems(), key=key)

Kent


More information about the Tutor mailing list