Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:按子字典值将字典键作为列表排序_Python_Sorting_Dictionary - Fatal编程技术网

Python:按子字典值将字典键作为列表排序

Python:按子字典值将字典键作为列表排序,python,sorting,dictionary,Python,Sorting,Dictionary,我的结构如下: structure = { 'pizza': { # other fields 'sorting': 2, }, 'burger': { # other fields 'sorting': 3, }, 'baguette': { # other fields 'sorting': 1, } } 从这个结构中,我需要按照内部字典的排序字段

我的结构如下:

structure = {
    'pizza': {
        # other fields
        'sorting': 2,
    },
    'burger': {
        # other fields
        'sorting': 3,
    },
    'baguette': {
        # other fields
        'sorting': 1,
    }
}
从这个结构中,我需要按照内部字典的
排序
字段对外部字典的键进行排序,因此输出是
['baguette','pizza','burger']

有一种足够简单的方法可以做到这一点吗?

list.sort()方法和
sorted()
内置函数使用一个
key
参数,该参数是为每个要排序的项调用的函数,并且根据该键函数的返回值对项进行排序。因此,编写一个函数,在
结构中获取一个键,并返回要排序的内容:

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

您可以使用
sorted
内置函数

sorted(structure.keys(), key = lambda x: structure[x]['sorting'])
我没有忘记
.keys()
,它不是必需的。DICT在迭代时会生成密钥。