如何在字典中创建值的外观直方图?

时间:2012-04-24 18:23:34

标签: python dictionary count histogram

使用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 个答案:

答案 0 :(得分: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

答案 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