Python按键key或值value对字典进行排序

个人博客,欢迎来撩 fangzengye.com

 

1.按键key

对字典内部排序

dict={}

sorted(dict)默认按键升序

对字典列表排序

lis = [{ "name" : "Taobao", "age" : 100},  
{ "name" : "Runoob", "age" : 7 }, 
{ "name" : "Google", "age" : 100 }, 
{ "name" : "Wiki" , "age" : 200 }] 

通过 age 升序排序

print ("列表通过 age 升序排序: ")
print (sorted(lis, key = lambda i: i['age']) )

print ("\r")

先按 age 排序,再按 name 排序

print ("列表通过 age 和 name 排序: ")
print (sorted(lis, key = lambda i: (i['age'], i['name'])) )

print ("\r")

按 age 降序排序

print ("列表通过 age 降序排序: ")
print (sorted(lis, key = lambda i: i['age'],reverse=True) )

善用sort() 或 sorted(),

a.sort() 已改变其结构,b = a.sort() 是错误的写法! 而 sorted(a, ...)并没有改变a的结构。

 

、参考资料

https://www.runoob.com/python3/python-sort-dictionaries-by-key-or-value.html

https://www.cnblogs.com/cmybky/p/11772695.html

posted @ 2020-12-16 21:40  开源的Boy  阅读(199)  评论(0)    收藏  举报