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']
You can use the sorted
builtin function.
sorted(structure.keys(), key = lambda x: structure[x]['sorting'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With