How does python sort dictionaries by key or numeric value
This article mainly introduces how python sorts dictionaries according to keys or values. It is very detailed and has a certain reference value. Friends who are interested must finish reading it.
How to sort dictionaries by key or numerical value # sort dictionaries by key or numerical value dict3 = {"low": 3, "irving": 6, "james": 1, "durant": 4} # Bronze player list3 = sorted (dict3.items (), key=lambda x: X [0]) dict3_keys = {for j for I, j in list3} print ("Bronze player keystroke sort:" Dict3_keys) list3 = sorted (dict3.items (), key=lambda x: X [1]) dict3_values = {isorted j for I, j in list3} print ("Bronze player by value:", dict3_values) # King player dict3_keys = {key: dict3 [key] for key in sorted (dict3)} print ("King player key order:", dict3_keys) dict3_values = {key: dict3 [key] for key in sorted (dict3) Key=dict3.get)} print ("Masters by value:", dict3_values)
Bronze player: this time I used the sorted built-in function to sort it, and then converted it to dictionary form. Two lines of code are done!
King player: bronze player your method will result in a waste of space resources in the process of conversion. I directly use the sorting of keys or values, and then use the sorted keys or values to construct the final dictionary, and the program is simple.
The above is all the content of the article "how to sort dictionaries by key or value by python". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!