[python] sort according to the value of the dictionary

    When looping through the dictionary, the traversed objects are the keys of the dictionary, and when comparing, the keys of the dictionary are also compared. What if you want to compare the values ​​of the dictionary? The previous article talked about the use of .items()|.keys()|.values() of the dictionary. This description is sorted by the size of the dictionary value.

import sys
import random
reload(sys)
sys.setdefaultencoding('utf-8')

Target

{'chen': 78, 'zhao': 70, 'xie': 67}
//这种字典,要对值进行按大小排序

generate dictionary

data_str=['xie','zhao','chen']
data_dic={k:random.randint(61,80) for k in data_str}

Common methods of dictionaries

print data_dic.keys()
//打印字典的所有键
print data_dic.values()
//打印字典的所有值
prinr data_dic.items()
//返回列表形式的字典,(就是列表)可以使用列表索引list[1]选择元素
print data_dic.viewkeys()
//打印字典所有键的集合,集合可以用去交集并集去重复

method one

print sorted(zip(data_dic.values(),data_dic.keys()))
//zip()函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
//结果:[(64, 'xie'), (72, 'chen'), (75, 'zhao')]

Method Two

print sorted(data_dic.items(),key=lambda x:x[1])
//sorted()中有key,cmp,reverse三种方法。
//结果:[('xie', 64), ('chen', 72), ('zhao', 75)]
//当然还可以转换成字典的形式
print dict([('xie', 64), ('chen', 72), ('zhao', 75)])

Generally speaking, the key is the most used, and the key accepts a function. For example, key=abs (absolute value), or define a function first, and then assign this function to key

  1. cmp specifies a custom comparison function that takes two arguments (elements of iterable) and returns a negative number if the first argument is less than the second argument; zero if the first argument is equal to the second argument; The first argument is greater than the second argument, and a positive number is returned. The default value is None.
  2. key specifies a function that takes one argument and is used to extract a key for comparison from each element. The default value is None.
  3. reverse is a boolean. If set to True, list elements will be sorted in reverse order.

Method three

from collections import OrderedDict
//OrderedDict能够对字典的值进行排序,只打印键,需要注意的是要先把字典赋给OrderedDict
data_dic = OrderedDict()
data_dic={k:random.randint(61,80) for k in data_str}
for x in data_dic:print x
结果:chen
     zhao
     xie

    The method of OrderedDict is suitable for only looking at the sorting of the keys. The application is generally used to view the keys after sorting by value.

Personal blog: www.langzi.fun
welcome to exchange Python development, security testing.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324855030&siteId=291194637