python-3.x - 使用列表值排序字典(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 变量dict
。d
我将改为调用 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]}
推荐阅读
- java - 线程“main”java.lang.IllegalArgumentException 中的异常:不支持列分数的数据类型 StringType
- php - 网站收到错误消息:mysqli_real_connect() 和 mysql_connect()
- ios - 如何在 iOS 中暂停/恢复/取消事件
- react-native - 如何从 react-native 正确导入 PermissionsAndroid?
- sql - 我可以在 SQL Azure 中编写数据分类脚本吗
- java - 如何在 Spring tp producer pl/sql 中传递数组?
- gcc - 如何指示 avr-gcc 优化 volatile 变量?
- android - Android Firebase FirebaseMessagingService RemoteMessage 优先级
- reactjs - 为什么 webpack 捆绑相同类型的文件不同?
- object - 如何获取对象列表中的单个字段值