简体   繁体   中英

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?

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']

您可以使用已sorted内置函数。

sorted(structure.keys(), key = lambda x: structure[x]['sorting'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM