Friloc
Friloc

Reputation: 43

How can I create a histogram of appearances of values in a dictionary?

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}

Upvotes: 1

Views: 1130

Answers (2)

georg
georg

Reputation: 214959

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.

Upvotes: 6

Donald Miner
Donald Miner

Reputation: 39893

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

Upvotes: 2

Related Questions