Python 字典的排序
2015-08-07 16:59
495 查看
在做 google-python-exercises 中 basic/wordcount.py 这个练习的时候,遇到了一个关于字典排序的问题。其实很简单,但是当时做的时候想了好久才找到思路(初学者嘛 ^_^)。于是想把这个问题记录下来。
按照 word 首字母进行排序,并将排序好的 word 和 count 以
按照 count 的大小由大到小进行排序,并将排序好的 word 和 count 以
输出为:
输出为:
这个地方采用了
题目
假设有如下字典(字典的键称作 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 -tt import sys def 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 5 g 100 hi 52 o 2
2. 按照字典的值进行排序
#!/usr/bin/python -tt import sys def 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 100 hi 52 a 5 o 2
这个地方采用了
sorted()函数的知识,当时做的时候没想起可以使用 key= 自定义排序,因此想了好久都没做出来。
相关文章推荐
- os.walk 目录遍历
- 使用Sublime text3 搭建python开发环境
- python中is和 == 的区别
- python 解析xml
- python xml sendEmail
- python 杀进程 判断文件是否存在 查看进程
- python引用和复制一个对象
- python udp 广播
- Python3 Counter类计算list中元素出现次数
- Python3 列表List或元组tuple中元素分解(赋值操作)
- Python 的列表排序
- 【Python】[函数] 函数的参数与递归函数
- python udpserver decorator 修饰类
- Python学习笔记06
- python之__name__属性
- python trackback的使用心得
- Python学习笔记
- 20150805-20150807 tradeDate-----python
- python none,null,,,,,类型
- python none,null,,,,,类型