鱼C论坛

 找回密码
 立即注册
查看: 3413|回复: 0

[技术交流] 字典的排序

[复制链接]
发表于 2020-9-18 12:34:37 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
因为.sort的排序方法只能用于列表,所以字典排序就要用built-ins函数的sorted
  1. dict1 = {6: 2, 8: 0, 1: 4, -5: 9, 10: 22}
  2. print('将字典按key默认排序:', sorted(dict1))
  3. print('将字典按key默认排序,并输出相应的value:', sorted(dict1.items()))
  4. print('将字典按key默认排序后翻转,并输出相应的value:', sorted(dict1.items(), reverse=True))
  5. print('将字典按value默认排序:', sorted(dict1.items(), key=lambda x: x[1]))
  6. print('获取字典的操作命令:\n', dir(dict1))
  7. print('排序没有改变初始的字典:', dict1)
  8. dict1[6] = 12
  9. print('改变了初始的字典关键字6的值',dict1)
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-27 09:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表