Python 字典的排序
来源:互联网 发布:mac air 怎么设置壁纸 编辑:程序博客网 时间:2024/05/18 20:53
在做 google-python-exercises 中 basic/wordcount.py 这个练习的时候,遇到了一个关于字典排序的问题。其实很简单,但是当时做的时候想了好久才找到思路(初学者嘛 ^_^)。于是想把这个问题记录下来。
题目
假设有如下字典(字典的键称作 word,其值称作 count):
word_count = {'a': 5, 'o': 2, 'g': 100, 'hi': 52}
- 按照 word 首字母进行排序,并将排序好的 word 和 count 以
word count
的形式打印出来。 - 按照 count 的大小由大到小进行排序,并将排序好的 word 和 count 以
word count
的形式打印出来。
1. 按照字典的键进行排序
#!/usr/bin/python -ttimport sysdef main(): word_count = {'a': 5, 'o': 2, 'g': 100, 'hi': 52} for word in sorted(word_count.keys()): print word, word_count[word]if __name__ == '__main__': main()
输出为:
a 5g 100hi 52o 2
2. 按照字典的值进行排序
#!/usr/bin/python -ttimport sysdef get_count(word_count_tuple): return word_count_tuple[1]def main(): word_count = {'a': 5, 'o': 2, 'g': 100, 'hi': 52} items = sorted(word_count.items(), key=get_count, reverse=True) for item in items: print item[0], item[1]if __name__ == '__main__': main()
输出为:
g 100hi 52a 5o 2
这个地方采用了 sorted()
函数的知识,当时做的时候没想起可以使用 key= 自定义排序,因此想了好久都没做出来。
0 0
- Python的字典排序
- Python 字典的排序
- python 字典的排序
- python -- 有序字典, 有序字典的排序
- 三、Python的字典排序
- 关于python字典的排序
- 对python字典的排序
- python的中字典的排序
- Python中最快的字典排序方法
- 传说中最快的python字典排序方法
- Python字典排序的简单实现
- Python中最快的字典排序方法
- python中字典的排序和复制
- python字典的遍历与排序
- Python 字典(dictionary)的排序
- python 按照字典的值进行排序
- Python字典按值排序、包含字典的列表按字典值排序的方法
- Python字典按值排序、包含字典的列表按字典值排序的方法
- 新米提督着任!
- MFC+OpenGL单文档制作三维图像
- Ubuntu14.04安装了Im-Switch后系统设置中不见了语言支持
- iOS 定时器(发送短信验证)
- 有意思的记录-Java
- Python 字典的排序
- Android实战经验之图像处理及特效处理的集锦(总结版)
- static_cast、dynamic_cast、reinterpret_cast和const_cast之间的区别,char int *p,int const*p
- ACM对拍程序
- IOS 触发按钮执行事件
- Session 过期时的处理方法之二:Redirect 到其它页面
- 事件冒泡与事件捕获
- sqlserver服务器更改主机名,维护计划无法删除
- gradle使用main运行java