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}
  1. 按照 word 首字母进行排序,并将排序好的 word 和 count 以 word count 的形式打印出来。
  2. 按照 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
原创粉丝点击