Python – 字典中的关联值频率
有时,在使用字典时,我们可能会遇到需要计算与记录列表中字典中的每个值关联的值的问题。这类问题比较特殊,但可以在开发领域有应用。让我们讨论可以执行此任务的特定方式。
方法:使用嵌套defaultdict() + Counter()
上述功能的组合可以用来解决这个问题。在此,我们使用嵌套的 defaultdict 来跟踪元素,元素的计数由 Counter() 完成。
# Python3 code to demonstrate working of
# Associated Values Frequencies in Dictionary
# Using defaultdict() + Counter()
from collections import defaultdict, Counter
# initializing list
test_list = [{'gfg' : 1, 'is' : 3, 'best' : 4},
{'gfg' : 3, 'is' : 2, 'best' : 4},
{'gfg' : 3, 'is' : 5, 'best' : 2},
{'gfg' : 5, 'is' : 2, 'best' : 1},
{'gfg' : 2, 'is' : 4, 'best' : 3},
{'gfg' : 1, 'is' : 3, 'best' : 5},
{'gfg' : 1, 'is' : 3, 'best' : 2}]
# printing original list
print("The original list is : " + str(test_list))
# Associated Values Frequencies in Dictionary
# Using defaultdict() + Counter()
res = defaultdict(Counter)
for sub in test_list:
for key, val in sub.items():
res[key][val] += 1
# printing result
print("The list after Frequencies : " + str(dict(res)))
输出 :
The original list is : [{‘gfg’: 1, ‘is’: 3, ‘best’: 4}, {‘gfg’: 3, ‘is’: 2, ‘best’: 4}, {‘gfg’: 3, ‘is’: 5, ‘best’: 2}, {‘gfg’: 5, ‘is’: 2, ‘best’: 1}, {‘gfg’: 2, ‘is’: 4, ‘best’: 3}, {‘gfg’: 1, ‘is’: 3, ‘best’: 5}, {‘gfg’: 1, ‘is’: 3, ‘best’: 2}]
The list after Frequencies : {‘gfg’: Counter({1: 3, 3: 2, 2: 1, 5: 1}), ‘is’: Counter({3: 3, 2: 2, 4: 1, 5: 1}), ‘best’: Counter({2: 2, 4: 2, 1: 1, 3: 1, 5: 1})}