Python: get dictionary keys as a list sorted by 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 external dictionary sorted by the sorting field of the internal dictionary, so the output is ['baguette', 'pizza', 'burger'] .

Is there a simple enough way to do this?

+4
source share
2 answers

The list.sort() method and the built-in sorted() function take a key argument, which is a function that causes each item to be sorted, and the item is sorted based on the return value of that key function. So, write a function that takes the key in structure and returns the thing you want to sort:

 >>> def keyfunc(k): ... return structure[k]['sorting'] ... >>> sorted(structure, key=keyfunc) ['baguettes', 'pizza', 'burger'] 
+9
source

You can use the built-in sorted function.

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

Source: https://habr.com/ru/post/1395969/


All Articles