In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article mainly introduces how python is sorted according to the size of the dictionary value. It has certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Let Xiaobian take you to understand it together.
How to sort by dictionary value
We know that the essence of the dictionary is a hash table, which itself cannot be sorted, but after Python 3.6, the dictionary can be traversed according to the order of insertion, which is an ordered dictionary, and the principle can be read why the dictionary is ordered after Python 3.6.
Knowing this, it is easy to sort the list of dictionary key pairs and then reinsert the new dictionary so that the new dictionary can traverse the output according to the size of the value. The code is as follows:
>>> xs = {'a': 4, ' b': 3, 'c': 2, ' d': 1} >> for k,v in xs.items():#Traverse dictionary... print(k,v) ... a 4 b 3 c 2 d 1 >>> new_order = sorted (xs.items(), key=lambda x: x[1]) #Sort the list of key pairs in the dictionary>> new_xs = { k : v for k,v in new_order} #Insert new dictionary into ordered list>> new_xs {'d': 1, 'c': 2, ' b': 3, 'a': 4} >> for k,v in new_xs.items():##The output of the new dictionary is ordered... print(k,v) ... d 1 c 2 b 3 a 4
You can also sort lists using the following methods:
>>> import operator >>> sorted (xs.items(), key=operator.itemgetter(1)) [('d ', 1),('c', 2),('b ', 3),('a', 4)] Thank you for reading this article carefully. I hope that Xiaobian will share the article "How python is sorted according to the size of dictionary values." This article is helpful to everyone. At the same time, I hope you will support it a lot. Pay attention to the industry information channel. More knowledge is waiting for you to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.