>>> d = {'a':66,'j':25,'h':12,'v':66,'p':19,'d':9,'e':89,'o':3,'s':66}
>>> by_key = sorted(d)
>>> by_key
['a', 'd', 'e', 'h', 'j', 'o', 'p', 's', 'v']
>>> for i in by_key:
print(i, d[i],end = '; ')
a 66; d 9; e 89; h 12; j 25; o 3; p 19; s 66; v 66;
直接sorted(dict)则是将字典按照键排序,sorted()排序后返回的只有键
如果要打印出键值对,还需要按键取值
>>> by_values = sorted(d.items(), key = lambda x: x[1])
>>> by_values
[('o', 3), ('d', 9), ('h', 12), ('p', 19), ('j', 25), ('a', 66), ('v', 66), ('s', 66), ('e', 89)]
# 值相同的情况下,按照键排序
>>> by_values = sorted(d.items(), key = lambda x: (x[1], x[0]))
>>> by_values
[('o', 3), ('d', 9), ('h', 12), ('p', 19), ('j', 25), ('a', 66), ('s', 66), ('v', 66), ('e', 89)]
# 降序排序
>>> by_values = sorted(d.items(), key = lambda x: (x[1], x[0]),reverse = True)
>>> by_values
[('e', 89), ('v', 66), ('s', 66), ('a', 66), ('j', 25), ('p', 19), ('h', 12), ('d', 9), ('o', 3)]
【注意】:
1、>>> by_values = sorted(d.items(), key = lambda x: (x[1], x[0]))
这里只能用sorted()方法,
而不能用d.sort(d.items(), key = lambda x: x[1])
否则会报错,字典没有sort()方法
2、>>> by_values = sorted(d.items(), key = lambda x: (x[1], x[0]))
这里将字典类型转化为了 列表类型(列表套元组)
后面按照数量多少输出时,不能用for k, v in d.items()
只能for i in d: --->print(i[0],':',i[1])
>>> lis = [{ "name" : "Taobao", "age" : 100},
{ "name" : "Runoob", "age" : 7 },
{ "name" : "Google", "age" : 100 },
{ "name" : "Wiki" , "age" : 200 }]
# 通过 age 升序排序
>>> sorted(lis, key = lambda i: i['age'])
[{'name': 'Runoob', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}]
# 先按 age 排序,再按 name 排序
>>> sorted(lis, key = lambda i: (i['age'], i['name']))
[{'name': 'Runoob', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}]
# 按 age 降序排序
>>> sorted(lis, key = lambda i: i['age'],reverse=True)
[{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Runoob', 'age': 7}]```