程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

python dictionary sorting method

編輯:Python

字典是“鍵-值對”的無序可變序列
在實際運用中,Sorting a dictionary is a relatively common operation,主要用到了python內置函數sorted(),This function can sort all iterable objects.
語法(python3):

sorted(iterable, key=None,reverse=False)

參數說明:
iterable:可迭代對象,即可以用for循環進行迭代的對象;
key:主要是用來進行比較的元素,只有一個參數,具體的函數參數取自於可迭代對象中,用來指定可迭代對象中的一個元素來進行排序;
reverse:排序規則,reverse=False升序(默認),reverse=True降序.

以下總結了sorted()Usage of the function for lexicographical sorting.
第一種:The most common single dictionary format data ordering

# 字典排序
a = {
'a': 3, 'c': 89, 'b': 0, 'd': 34}
# 按照字典的值進行排序
a1 = sorted(a.items(), key=lambda x: x[1])
# 按照字典的鍵進行排序
a2 = sorted(a.items(), key=lambda x: x[0])
print('按值排序後結果', a1)
print('按鍵排序後結果', a2)
print('結果轉為字典格式', dict(a1))
print('結果轉為字典格式', dict(a2))


原理:以a.items()返回的列表[(‘a’, 3), (‘c’, 89), (‘b’,0), (‘d’, 34)]中的每一個元素,作為匿名函數(lambda)的參數,x[0]即用“鍵”排序,x[1]即用“值”排序;Returns the result as a new list,可以通過dict()The function is converted to dictionary format.

第二種:字典列表排序

b = [{
'name': 'lee', 'age': 23}, {
'name': 'lam', 'age': 12}, {
'name': 'lam', 'age': 18}]
b1 = sorted(b, key=lambda x: x['name'])
b2 = sorted(b, key=lambda x: x['age'], reverse=True)
b3 = sorted(b, key=lambda x: (x['name'], -x['age']))
print('按name排序結果:', b1)
print('按age排序結果:', b2)
print('name相同按age降序排列:', b3)


原理:以列表bEach dictionary element inside is used as a parameter of the anonymous function,Then use the key to take the elements in the dictionary as the sorting condition as needed,如x[‘name’]即用nameSort by the value corresponding to the key.

-end-


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved