[英]How to sort dictionary values by frequency
Because I made my dict
file with append list.因为我用 append 列表制作了我的
dict
文件。 I have the following dict file:我有以下字典文件:
dict_1 = {'a':["1","2","d","d","d","1","2","2"],
'b':["1","2","e","e","5","5","5","6"]}
How do I sort the values by frequency
within the list
so I get output like:如何在
list
按frequency
对值进行排序,以便得到 output,如:
dict_1 = {'a':["d","d","d","2","2","2","1","1"],
'b':["5","5","5","e","e","6","2","1"]}
The order doesn't matter for strings of the same frequency对于相同频率的字符串,顺序无关紧要
I tried我试过
result=[]
for k,v in dict_1.items():
result.append(sorted(v, key = v.count,
reverse = True))
and got并得到
[['2', 'd', 'd', 'd', '2', '2', '1', '1'],
['5', '5', '5', 'e', 'e', '1', '2', '6']]
Something is wrong with the "2" in the first list.第一个列表中的“2”有问题。
Thanks.谢谢。
One way using collections.Counter
with dict
comprehension:一种使用
collections.Counter
和dict
理解的方法:
from collections import Counter
cnts = {k: Counter(v) for k, v in dict_1.items()}
Or without Counter
, using list.count
:或者没有
Counter
,使用list.count
:
cnts = {k: {i: v.count(i) for i in set(v)} for k, v in dict_1.items()}
Then do sort:然后进行排序:
{k: sorted(v, key=lambda x: (cnts[k][x], x), reverse=True) for k, v in dict_1.items()}
Output: Output:
{'a': ['d', 'd', 'd', '2', '2', '2', '1', '1'],
'b': ['5', '5', '5', 'e', 'e', '6', '2', '1']}
Note:笔记:
key
for sorted
returns tuple of (count, itself)
so that same items remain grouped. sorted
的key
返回(count, itself)
的元组,以便相同的项目保持分组。
Here is a way to do it without collections module in python.这是一种在 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: Output:
['2', 'd', 'd', 'd', '2', '2', '1', '1']
['5', '5', '5', 'e', 'e', '1', '2', '6']
You can read more about sorted()
from this link您可以从此链接阅读有关
sorted()
的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.