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 Counter
x = 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值