Because I made my dict
file with append list. 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:
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.
Thanks.
One way using collections.Counter
with dict
comprehension:
from collections import Counter
cnts = {k: Counter(v) for k, v in dict_1.items()}
Or without Counter
, using 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:
{'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.
Here is a way to do it without collections module in python.
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']
You can read more about sorted()
from this link
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.