Python - 查找特定键的每个值的出现次数
给定一个字典列表,对于一个特定的键,找出该键的每个值出现的次数。
Input : test_list = [{‘gfg’ : 3, ‘best’ : 4}, {‘gfg’ : 3, ‘best’ : 5},
{‘gfg’ : 4, ‘best’ : 4}, {‘gfg’ : 7, ‘best’ : 4} ], K = ‘gfg’
Output : [{3: 2}, {4: 1}, {7: 1}]
Explanation : gfg has 2 occurrences of 3 as values.
Input : test_list = [{‘gfg’ : 3, ‘best’ : 4}, {‘gfg’ : 3, ‘best’ : 5},
{‘gfg’ : 4, ‘best’ : 4}, {‘gfg’ : 7, ‘best’ : 4} ], K = ‘best’
Output : [{4: 3}, {5: 1}]
Explanation : best has 3 occurrences of 4 as values.
方法 #1:使用groupby() + 字典理解
在这里,我们使用 groupby() 对键的值进行分组,并使用字典理解和 len() 组合和提取值频率。
Python3
# Python3 code to demonstrate working of
# Values Frequency grouping of K in dictionaries
# Using groupby() + dictionary comprehension
from itertools import groupby
# initializing list
test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},
{'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'gfg'
# groupby() used to group values and len() to compute Frequency
res = [{key: len(list(val))} for key, val in groupby(test_list, lambda sub: sub[K])]
# printing result
print("The Values Frequency : " + str(res))
Python3
# Python3 code to demonstrate working of
# Values Frequency grouping of K in dictionaries
# Using Counter()
from collections import Counter
# initializing list
test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},
{'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'gfg'
# groupby() used to group values and len() to compute Frequency
res = dict(Counter(sub[K] for sub in test_list))
# printing result
print("The Values Frequency : " + str(res))
输出:
The original list is : [{‘gfg’: 3, ‘best’: 4}, {‘gfg’: 3, ‘best’: 5}, {‘gfg’: 4, ‘best’: 4},
{‘gfg’: 7, ‘best’: 4}]
The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]
方法 #2:使用Counter()
在这里,执行频率检查的任务是使用 Counter() 完成的。在单个字典中返回结果。
蟒蛇3
# Python3 code to demonstrate working of
# Values Frequency grouping of K in dictionaries
# Using Counter()
from collections import Counter
# initializing list
test_list = [{'gfg' : 3, 'best' : 4}, {'gfg' : 3, 'best' : 5},
{'gfg' : 4, 'best' : 4}, {'gfg' : 7, 'best' : 4} ]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 'gfg'
# groupby() used to group values and len() to compute Frequency
res = dict(Counter(sub[K] for sub in test_list))
# printing result
print("The Values Frequency : " + str(res))
输出:
The original list is : [{‘gfg’: 3, ‘best’: 4}, {‘gfg’: 3, ‘best’: 5}, {‘gfg’: 4, ‘best’: 4},
{‘gfg’: 7, ‘best’: 4}]
The Values Frequency : [{3: 2}, {4: 1}, {7: 1}]