首页 > 解决方案 > 使用列表值排序字典(python)

问题描述

dict={"a":[1,2,3,12],"b":[5,6,7,8],"c":[9,10,11,4]}

这是我的字典,我想dict按每个值列表的最后一个索引进行排序……有可能吗?我的意思是我想dict按这个数字 4,8,12 排序并打印出来。所以输出将是:

{'a': [9, 10, 11, 4], 'b': [5, 6, 7, 8], 'c': [1,2,3,12]}

标签: python-3.xdictionary

解决方案


您不应该命名 Python 变量dictd我将改为调用 dict 。

$ python
Python 3.8.6 (default, Jan 27 2021, 15:42:20)
[GCC 10.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> d = {"a":[1,2,3,12],"b":[5,6,7,8],"c":[9,10,11,4]}

这会产生字典项目的排序列表:

>>> sorted(list(d.items()), key=lambda x: x[1][3])
[('c', [9, 10, 11, 4]), ('b', [5, 6, 7, 8]), ('a', [1, 2, 3, 12])]

现在我们可以得到排序的字典:

>>> dict(sorted(list(d.items()), key=lambda x: x[1][3]))
{'c': [9, 10, 11, 4], 'b': [5, 6, 7, 8], 'a': [1, 2, 3, 12]}

推荐阅读