Python – 频率分组字典
有时,在使用Python字典时,我们可能会遇到需要对字典数据进行分组的问题,即我们需要按照其频率对所有相似的字典键进行分组。这类问题在Web开发领域有其应用。让我们讨论可以执行此任务的某些方式。
Input : test_list = [{‘best’: 2, ‘Gfg’: 1}, {‘best’: 2, ‘Gfg’: 1}]
Output : [{‘freq’: 2, ‘Gfg’: 1}]
Input : test_list = [{‘Gfg’: 1, ‘best’: 2}, {‘Gfg’: 2, ‘best’: 1}]
Output : [{‘Gfg’: 1, ‘freq’: 1}, {‘Gfg’: 2, ‘freq’: 1}]
方法 #1:使用defaultdict()
+ 列表推导
上述功能的组合可用于执行此任务。在此,我们用整数初始化 defaultdict 以获得频率,并使用列表推导来编译结果字典。
# Python3 code to demonstrate working of
# Frequency Grouping Dictionary
# Using defaultdict() + list comprehension
from collections import defaultdict
# initializing list
test_list = [{'Gfg' : 1, 'best' : 2},
{'Gfg' : 1, 'best' : 2},
{'Gfg' : 2, 'good' : 3},
{'Gfg' : 2, 'best' : 2},
{'Gfg' : 2, 'good' : 3}]
# printing original list
print("The original list is : " + str(test_list))
# Frequency Grouping Dictionary
# Using defaultdict() + list comprehension
temp = defaultdict(int)
for sub in test_list:
key = sub['Gfg']
temp[key] += 1
res = [{"Gfg": key, "freq": val} for (key, val) in temp.items()]
# printing result
print("The frequency dictionary : " + str(res))
输出 :
The original list is : [{‘Gfg’: 1, ‘best’: 2}, {‘Gfg’: 1, ‘best’: 2}, {‘good’: 3, ‘Gfg’: 2}, {‘Gfg’: 2, ‘best’: 2}, {‘good’: 3, ‘Gfg’: 2}]
The frequency dictionary : [{‘Gfg’: 1, ‘freq’: 2}, {‘Gfg’: 2, ‘freq’: 3}]