Python sort dictionary by key or value

Document 对象参考手册Python3 Examples

Given a dictionary, sort it by key or value.

Example 1: Sort by key

def dictionairy(): # Declare dictionary key_value ={} # Initialize key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print ("Sort by key:") # sorted(key_value) returns a re-sorted list # Sort dictionary by key for i in sorted (key_value) : print ((i, key_value[i]), end =" ") def main(): # Call the function dictionairy() # Main function if __name__=="__main__": main()

Executing the above code outputs the following result:

按键(key)排序:
(1, 2) (2, 56) (3, 323) (4, 24) (5, 12) (6, 18) 

Example 2: Sort by value

def dictionairy(): # Declare dictionary key_value ={} # Initialize key_value[2] = 56 key_value[1] = 2 key_value[5] = 12 key_value[4] = 24 key_value[6] = 18 key_value[3] = 323 print ("Sort by value:") print(sorted(key_value.items(), key = lambda kv:(kv[1], kv[0]))) def main(): dictionairy() if __name__=="__main__": main()

Executing the above code outputs the following result:

按值(value)排序:
[(1, 2), (5, 12), (6, 18), (4, 24), (2, 56), (3, 323)]

Example 3: Sort a list of dictionaries

lis = [{ "name" : "Taobao", "age" : 100}, { "name" : "Example", "age" : 7 }, { "name" : "Google", "age" : 100 }, { "name" : "Wiki" , "age" : 200 }] # Sort by age in ascending order print ("List sorted by age in ascending order:") print (sorted(lis, key = lambda i: i['age']) ) print ("\r") # Sort by age first, then by name print ("List sorted by age and name:") print (sorted(lis, key = lambda i: (i['age'], i['name'])) ) print ("\r") # Sort by age in descending order print ("List sorted by age in descending order:") print (sorted(lis, key = lambda i: i['age'],reverse=True) )

Executing the above code outputs the following result:

列表通过 age 升序排序: 
[{'name': 'Example', 'age': 7}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Wiki', 'age': 200}]

列表通过 age 和 name 排序: 
[{'name': 'Example', 'age': 7}, {'name': 'Google', 'age': 100}, {'name': 'Taobao', 'age': 100}, {'name': 'Wiki', 'age': 200}]

列表通过 age 降序排序: 
[{'name': 'Wiki', 'age': 200}, {'name': 'Taobao', 'age': 100}, {'name': 'Google', 'age': 100}, {'name': 'Example', 'age': 7}]

Document 对象参考手册Python3 Examples

Other extensions