[英]How to sort dictionary values by frequency
因为我用 append 列表制作了我的dict
文件。 我有以下字典文件:
dict_1 = {'a':["1","2","d","d","d","1","2","2"],
'b':["1","2","e","e","5","5","5","6"]}
如何在list
按frequency
对值进行排序,以便得到 output,如:
dict_1 = {'a':["d","d","d","2","2","2","1","1"],
'b':["5","5","5","e","e","6","2","1"]}
对于相同频率的字符串,顺序无关紧要
我试过
result=[]
for k,v in dict_1.items():
result.append(sorted(v, key = v.count,
reverse = True))
并得到
[['2', 'd', 'd', 'd', '2', '2', '1', '1'],
['5', '5', '5', 'e', 'e', '1', '2', '6']]
第一个列表中的“2”有问题。
谢谢。
一种使用collections.Counter
和dict
理解的方法:
from collections import Counter
cnts = {k: Counter(v) for k, v in dict_1.items()}
或者没有Counter
,使用list.count
:
cnts = {k: {i: v.count(i) for i in set(v)} for k, v in dict_1.items()}
然后进行排序:
{k: sorted(v, key=lambda x: (cnts[k][x], x), reverse=True) for k, v in dict_1.items()}
Output:
{'a': ['d', 'd', 'd', '2', '2', '2', '1', '1'],
'b': ['5', '5', '5', 'e', 'e', '6', '2', '1']}
笔记:
sorted
的key
返回(count, itself)
的元组,以便相同的项目保持分组。
这是一种在 python 中没有 collections 模块的方法。
dict_1 = {'a':["1","2","d","d","d","1","2","2"],
'b':["1","2","e","e","5","5","5","6"]}
for items in dict_1: # looping through the dictionary to get every key value pair in the dictionary
l = dict_1.get(items) # getting the value of every key value pair in the dictionary. Here "l" is short for "list"
print(sorted(l, key=l.count, reverse=True)) # sorting it according to frequency of the element in the list.
Output:
['2', 'd', 'd', 'd', '2', '2', '1', '1']
['5', '5', '5', 'e', 'e', '1', '2', '6']
您可以从此链接阅读有关sorted()
的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.