2012-04-24 26 views
1

使用Python 2.6:如何创建字典中值的外观直方图?

我有一个字典,其中每个键包含一个值列表。

我想查看字典中的所有值,并计算每个键在每个键上出现的次数。

我一直在寻找itervalues()或

for value in dictionary.values(): 

一开始,也是.Count之间()函数,但我需要返回一个直方图。

例如:

print dictionary 

将返回

{'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']} 

和我想要的东西告诉我:

{'spam' : 3, 'eggs' : 1, 'cheese': 2, 'goats' : 1} 

回答

2

遍历相应值的列表,并将它们添加到一个新的字典通过逐一增加。

# start with an empty output dictionary 
out = {} 

# iterate through the keys in the dictionary 
for key in p: 
    # iterate through the values in the sublist 
    for val in p[key]: 
     # check to see if we've seen this one before 
     if not out.has_key(val): 
     # if not, start it out at 0 
     out[val] = 0 

     # increment by one because we've seen it once more 
     out[val] += 1 

print out 
+0

太棒了!至少目前为止。看起来计数有些偏差,但是,只有少数几个值。让我看看为什么。 – Friloc 2012-04-24 18:36:24

+0

这似乎是程序的前一部分的问题。你的柜台确实有效。谢谢!! – Friloc 2012-04-24 18:44:33

6
from collections import Counter 

d = {'test' : ['spam', 'eggs', 'cheese', 'spam'], 'test2' : ['spam', 'cheese', 'goats']} 
c = Counter(sum(d.values(), [])) 
# or c = Counter(x for a in d.values() for x in a) 
print c.most_common() 

## [('spam', 3), ('cheese', 2), ('eggs', 1), ('goats', 1)] 

对于Python 2.6使用this recipe

+0

不错。不知道这个。 – 2012-04-24 18:32:17

+0

计数器是2.7中的新增功能,因此我使用2.6来询问。 – Friloc 2012-04-24 18:40:29

+0

@ thg435谢谢 – Friloc 2012-04-24 18:42:10