注:学习笔记来源于自己在学习Python过程中遇到的小问题及对网络诸多大牛提供的方法的实践。
此Python版本:Python 3.3.5
Python 字典
一、字典排序
1.根据“键key”或“键值value”对字典内元素进行排序。
2.函数原型:
sorted(dic,value,reverse)
dic为比较函数,value为排序的对象(这里指key或value)
reverse:True——降序,False——升序(默认)
3.举例
(1)key和value都是int型
>>>dict1 = {1: 3, 2: 5, 3: 1}
>>> sorted(dict1.items(), key = lambda d:d[1], reverse = True)
[(2, 5), (1, 3), (3, 1)]
#按value排序,降序
#其中d是参数,任意命名皆可,第一个参数传给第二个参数,第二个参数取出其中的key([0])或者value([1])
#lambda用来创建匿名函数,但不会把这个函数对象赋给一个标识符(懵懂。。待定)
>>> sorted(dict2.items(), key = lambda d:d[0], reverse = True)
[(3, 1), (2, 5), (1, 3)]
#按key排序,降序
(2)key和value都是str型
>>> dict1 = {'1':'3','2':'5','3':'1'}
>>> sorted(dict1.items(), key = lambda d:d[1], reverse = True)
[('2', '5'), ('1', '3'), ('3', '1')]
>>> dict1 = {'a':'3','b':'5','c':'1'}
>>> sorted(dict1.items(), key = lambda d:d[1], reverse = True)
[('b', '5'), ('a', '3'), ('c', '1')]
(3)key为str型,value为int型
>>> dict1 = {'a':3, 'b':5, 'c':1}
>>> sorted(dict1.items(), key = lambda d:d[1], reverse = True)
[('b', 5), ('a', 3), ('c', 1)]