Reputation: 21
I need to count the number of times different values are listed in my dictionary. The problem is that I cant figure out how to count the values.
print dic
{'KLOI98': ['Martha Miller', '4563', 'Vet_Parking'], 'TY5678': ['Jane Miller', '8987', 'AgHort_Parking'], 'WER546': ['Olga Grey', '9898', 'Creche_Parking'], 'HUY768': ['Wilbur Matty', '8912', 'Creche_Parking'], 'EDF768': ['Bill Meyer', '2456', 'Vet_Parking'], 'DF7800': ['Jacko Frizzle', '4532', 'Creche_Parking'], 'JU9807': ['Jacky Blair', '7867', 'Vet_Parking'], 'GEF123': ['Jill Black', '3456', 'Creche_Parking'], 'ADF645': ['Cloe Freckle', '6789', 'Vet_Parking'], 'GH7682': ['Clara Hill', '7689', 'AgHort_Parking'], 'ABC234': ['Fred Greenside', '2345', 'AgHort_Parking']}
and my code:
for k, v in dic.items():
print "%s: %s" % (k, v)
All I'm trying to do is count the number of Vet,AgHort and Creche parks. I cant change the key as the rest of my script works with it.
Thanks for the help.
Should be simple, but I just cant crack it.
Upvotes: 3
Views: 8137
Reputation: 15702
You just have to reduce your data to the required data and then use a Counter
:
from collections import Counter
print Counter([x[2] for x in data.values()])
It displays:
Counter({'Creche_Parking': 4, 'Vet_Parking': 4, 'AgHort_Parking': 3})
Upvotes: 0
Reputation: 21
Counter requires you to be using Python 2.7 or greater. For those of us who have to use 2.6 or prior (don't laugh - there are a couple of major analytics libraries they haven't updated yet...)....
result = {}
for item in [value[2] for value in test.values()]:
result[item]=result.get(item,0)+1
print result
I'm using a list comprehension to unpack the data - rationale was this this could be tested as a standalone element, before adding the complexity of rolling up the data. There is actually more than one way to handle this part :)
Upvotes: 2
Reputation: 24788
from collections import Counter
items = Counter(val[2] for val in dic.values())
Upvotes: 12