python sorted函数按value值对字典排序

来源:互联网 发布:linux echo $ 编辑:程序博客网 时间:2024/06/15 23:48

1.sorted(d.items(),key=lambda item:item[1] ,reverse=False)

注意得到的是个list,要得到字典前面加dict()

>>> d={"one":45,"two":24,"three":78,"four":98}>>> d.items()dict_items([('one', 45), ('two', 24), ('three', 78), ('four', 98)])>>> sorted(d.items(),key=lambda item:item[1],reverse=False) [('two', 24), ('one', 45), ('three', 78), ('four', 98)]>>> dict(sorted(d.items(),key=lambda item:item[1],reverse=False) ){'two': 24, 'one': 45, 'three': 78, 'four': 98}

2.sorted()传入dict时没有加items,则默认比较的是dict的key,所以在key=function()参数x也是dict的key

from collections import Counterx = Counter({'a':5, 'b':3, 'c':7})sorted(x)>>['a', 'b', 'c']sorted(x.items())>>[('a', 5), ('b', 3), ('c', 7)]tf_counter = Counter(gen_tf(data))    df_counter = Counter(gen_df(data))    vocab = sorted(df_counter,              key=lambda x: (df_counter.get(x),tf_counter.get(x)),              reverse=True)                   #注意这儿df_counter没加items(),所有lambda后的x默认是key值
原创粉丝点击