python - 根据另一个字典对列表进行排序

标签 python sorting dictionary

我有一个列表和一个字典:

list1 = ["a", "b", "c", "d"]

dict1 = 
{
    "a": 4,
    "b": 3,
    "c": 5,
    "d": 9,
    "e": 2,
    "f": 8
}


我要做的是根据dict1中对应的值对list1进行排序。

对于上面的例子,我希望列表变成["b", "a", "c", "d"],根据它们的值排序..

我知道它应该是这样的......

list2 = sorted(list1, key=dict1[x])

但是我卡住了:((

任何帮助将不胜感激

最佳答案

关键参数应该是一个函数。

例如,使用绑定(bind)方法 dict.__getitem__dict.get :

>>> list1 = ["a", "b", "c", "d"]
>>> dict1 = { "a": 4, "b": 3, "c": 5, "d": 9, "e": 2, "f": 8 }
>>> sorted(list1, key=dict1.__getitem__)
['b', 'a', 'c', 'd']

关于python - 根据另一个字典对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19944812/

相关文章:

C++ 数组排序,内存错误?

algorithm - 保序散列函数

python - 为什么更新一个字典对象会影响其他对象?

c++ - 在 map 中使用前类的前向声明错误

python - 如何导入我自己的 python 文件?

python - 语法错误 : unexpected character after line continuation character in python

python - 线程 : It is not safe to use pixmaps outside the GUI thread

python - 根据值对字典进行排序

用于增量值的 python 字典

python - 一组 float