Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Get dictionary keys as list sorted by sub dictionary value

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?

like image 436
Martin Avatar asked Dec 05 '22 18:12

Martin


2 Answers

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']
like image 145
Thomas Wouters Avatar answered Jan 08 '23 08:01

Thomas Wouters


You can use the sorted builtin function.

sorted(structure.keys(), key = lambda x: structure[x]['sorting'])
like image 37
Praveen Gollakota Avatar answered Jan 08 '23 06:01

Praveen Gollakota