📌  相关文章
📜  Python - 查找特定键的每个值的出现次数

📅  最后修改于: 2022-05-13 01:54:39.629000             🧑  作者: Mango

Python - 查找特定键的每个值的出现次数

给定一个字典列表,对于一个特定的键,找出该键的每个值出现的次数。

方法 #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))


输出:

方法 #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))

输出: