Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.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_List_Sorting_Dictionary - Fatal编程技术网

Python 使用转换函数对字典值进行排序

Python 使用转换函数对字典值进行排序,python,list,sorting,dictionary,Python,List,Sorting,Dictionary,根据以下词典: a = {'foo': {'n': 'one', 'text': 'bla'}, 'bar': {'n': 'two', 'text': 'blah'}, 'baz': {'n': 'three', 'text': 'blabla'}} 我想要一个按n中的值排序的结果列表: ['foo', 'bar', 'baz'] 假设n中的值是常量且已知的(所有值)。因此,在示例中,n中只允许1、2和3的值 我假设这必须是a.items()上的sorted()与转换l

根据以下词典:

a = {'foo': {'n': 'one', 'text': 'bla'},
     'bar': {'n': 'two', 'text': 'blah'},
     'baz': {'n': 'three', 'text': 'blabla'}}
我想要一个按
n
中的值排序的结果列表:

['foo', 'bar', 'baz']
假设
n
中的值是常量且已知的(所有值)。因此,在示例中,
n
中只允许
1
2
3
的值


我假设这必须是
a.items()
上的
sorted()
与转换lambda函数的某种组合,转换lambda函数将
one
替换为1,依此类推,这样排序函数才能实际工作。但我似乎不能把它串起来让它工作。

我不确定我是否理解,但是

a = {'foo': {'n': 'one', 'text': 'bla'},
     'bar': {'n': 'two', 'text': 'blah'},
     'baz': {'n': 'three', 'text': 'blabla'}}


order = ['three', 'one', 'two']

r = sorted(a, key=lambda k: order.index(a[k]['n']))
正如您提到的,由于n中的值是常量且已知的,因此可以使用
映射。诀窍在于,您需要在字典中映射给定集合的每个值。因此,一旦您准备好映射器,使用
排序
函数的
参数,就可以使用它映射答案

>>> a = {'foo': {'n': 'one', 'text': 'bla'},
...      'bar': {'n': 'two', 'text': 'blah'},
...      'baz': {'n': 'three', 'text': 'blabla'}}
>>> mapping_dict = {'one':1,'two':2,'three':3}
>>> sorted(a.keys(),key = lambda x: mapping_dict[a[x]['n']])
['foo', 'bar', 'baz']

sorted(a.keys(),lambda x:a[x]['n'])
@BhargavRao你没读第二句吗?我想将字典中的值排序到一个列表中。您可以对任何内容的值进行排序,这与词典无关。@这似乎不起作用,而且它会按字母顺序对
n
@mart1n中的值进行排序。标题不正确。我没有超过冠军。我现在读。很抱歉