Take the 2-minute tour ×

I have the following structure:

structure = {
    'pizza': {
        # other fields
        'sorting': 2,
    'burger': {
        # other fields
        'sorting': 3,
    'baguette': {
        # other fields
        'sorting': 1,

From this structure I need the keys of the outer dictionary sorted by the sorting field of the inner dictionary, so the output is ['baguette', 'pizza', 'burger'].

Is there a simple enough way to do this?

share|improve this question

2 Answers 2

up vote 9 down vote accepted

The list.sort() method and the sorted() builtin function take a key argument, which is a function that's called for each item to be sorted, and the item is sorted based on the returnvalue of that keyfunction. So, write a function that takes a key in structure and returns the thing you want to sort on:

>>> def keyfunc(k):
...     return structure[k]['sorting']
>>> sorted(structure, key=keyfunc)
['baguettes', 'pizza', 'burger']
share|improve this answer
+1 for explanation. –  DSM Feb 11 '12 at 20:59
You forgot .keys(), but except for that this works! –  Martin Feb 11 '12 at 21:53
I did not forget .keys(), it isn't necessary. Dicts yield keys when you iterate over them. –  Thomas Wouters Feb 11 '12 at 21:59

You can use the sorted builtin function.

sorted(structure.keys(), key = lambda x: structure[x]['sorting'])
share|improve this answer

Your Answer


