Python -如何按使用频率最高的值对字典进行排序

bqucvtff  于 2023-03-11  发布在  Python
关注(0)|答案(2)|浏览(217)

比如我有
[{1:“一百”,二:“一百零二”,三:“101”,4:“100”,5:“102”,6:“100”,7:“102”,8:“101”,9:'100'}]
我想把它分类成
[{1:“一百”,四:“一百”,六:“100”,9:“100”,2:“102”,5:“102”,7:“102”,3:“101”,8:“101”}]
因此,它必须完全基于哪种价值观是最常见的。
有人用基于键的排序方法做到了这一点:Sort dictionary by key with highest frequency
我想不通,请帮帮忙!谢谢!

hmae6n7t

hmae6n7t1#

代码:

from collections import Counter

dic={1: '100', 2: '102', 3: '101', 4: '100', 5: '102', 6: '100', 7: '102', 8: '101', 9: '100'}

value_counts = Counter(dic.values())

#print(value_counts) # Counter({'100': 4, '102': 3, '101': 2})
res={}
for value, count in value_counts.most_common():
    #print(value,count)     #100 4  102 3  101 2
    for key, val in dic.items():
        if val == value:
            res[key] = val
print(res)

输出:

{1: '100', 4: '100', 6: '100', 9: '100', 2: '102', 5: '102', 7: '102', 3: '101', 8: '101'}
ycggw6v2

ycggw6v22#

输入给定字典,

a = [{1: '100', 2: '102', 3: '101', 4: '100', 5: '102', 6: '100', 7: '102', 8: '101', 9: '100'}]

查找dict a中的值的计数。

from collections import Counter
a_counted_dict = Counter(a[0].values())
print("Counted Value dict : "+str(a_counted_dict))

计数值指令:计数器({'100':4、“102”:3、“101”:第2条)

按关键字排序字典,

a_sorted_by_key = dict(sorted(a[0].items()))
print(a_sorted_by_key)

{1:“100”,2:“102”,3:“101”,4:“100”,5:“102”,6:“100”,7:“102”,8:“一百零一”,九:“一百”}

**再次按字典的值排序,**因此相同的值将合并,

a_sorted_by_key_and_value = dict(sorted(a_sorted_by_key.items(), key=lambda item:item[1]))
print(a_sorted_by_key_and_value)

{1:“100”,4:“100”,6:“100”,9:“100”,3:“101”,8:“101”,2:“102”,5:“102”,7:“102”}

再次按计数频率对字典排序,

a_sorted_by_key_and_value_and_valuefrequency = dict(sorted(a_sorted_by_key_and_value.items(), key=lambda item: a_counted_dict[item[1]], reverse= True))

{1:“100”,4:“100”,6:“100”,9:“100”,2:“102”,5:“102”,7:“102”,3:“101”,8:“101”}
那是你预期的结果。

相关问题