📜  Python – 字典中值的频率

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

Python – 字典中值的频率

有时,在使用Python字典时,我们可能会遇到需要提取字典中值的频率的问题。这是一个相当普遍的问题,并且在许多领域都有应用,包括 Web 开发和日常编程。让我们讨论可以执行此任务的某些方式。

方法 #1:使用defaultdict() + 循环
上述功能的组合可以用来解决这个问题。在此,我们使用 defaultdict() 用整数初始化计数器字典,并使用循环以蛮力方式递增计数器。

# Python3 code to demonstrate working of 
# Dictionary Values Frequency
# Using defaultdict() + loop
from collections import defaultdict
  
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Dictionary Values Frequency
# Using defaultdict() + loop
res = defaultdict(int)
for key, val in test_dict.items():
    res[val] += 1
      
# printing result 
print("The frequency dictionary : " + str(dict(res))) 
输出:
The original dictionary : {'Gfg': 3, 'code': 2, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}

方法 #2:使用Counter() + values()
上述功能的组合可以用来解决这个问题。在此,我们使用 values() 执行提取值的任务,并使用 Counter() 执行频率计数器。

# Python3 code to demonstrate working of 
# Dictionary Values Frequency
# Using Counter() + values()
from collections import Counter
  
# initializing dictionary
test_dict = {'ide' : 3, 'Gfg' : 3, 'code' : 2}
  
# printing original dictionary
print("The original dictionary : " + str(test_dict))
  
# Dictionary Values Frequency
# Using defaultdict() + loop
res = Counter(test_dict.values())
      
# printing result 
print("The frequency dictionary : " + str(dict(res))) 
输出:
The original dictionary : {'code': 2, 'Gfg': 3, 'ide': 3}
The frequency dictionary : {2: 1, 3: 2}