1

Using python 2.6:

I have a dictionary where each key contains a list of values.

I want to look at all the values in the dictionary and tally how many times each appears across all keys.

I have been looking at itervalues() or

for value in dictionary.values():

for a start, and also the .count() function, but I need to return a histogram.

for example:

print dictionary

would return

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

and I want something to tell me:

{'spam' : 3, 'eggs' : 1, 'cheese': 2, 'goats' : 1}
Friloc
  • 43
  • 1
  • 8

2 Answers2

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)]

For python 2.6 use this recipe.

georg
  • 211,518
  • 52
  • 313
  • 390
2

Iterate through the list of values and add them to a new dictionary by incrementing one by one.

# 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
Donald Miner
  • 38,889
  • 8
  • 95
  • 118
  • Great! so far at least. It appears the count is off somewhat, however, just for a few of the values. Let me look into why. – Friloc Apr 24 '12 at 18:36
  • this appears to be an issue with a previous part of the program. your counter does work. Thanks!! – Friloc Apr 24 '12 at 18:44