Reputation: 105
For example, if I have a dictionary that lists farm animals, it would be as follows:
{"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
How would I be able to count the number of times each value appears for the corresponding key? I want groupA cow 1, groupA lamb 3, groupB cow 2. The even trickier part is that the dictionary is not fixed, it needs to be dynamic. There may be more keys that go on past groupB (ex. groupC, group D) and might have more or less values associated with it. I have figured out a static way by popping out each key then using the if function to see what it contains then put a counter to it. (The only two animals will be either cow or lamb). I unfortunately cannot determine how to do this dynamically because I will never know how many keys there will be. Thank you guys so much for the help. I couldn't find the answer anywhere and am extremely frustrated at the moment.
Upvotes: 0
Views: 939
Reputation: 1
rite={"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
for i,j in rite.iteritems():
b=set(j)
for k in b:
print i,k,j.count(k)
Upvotes: 0
Reputation: 304413
Another iterpretation using Counter
>>> from collections import Counter
>>> D = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
>>> Counter((k,v) for k in D for v in D[k])
Counter({('groupA', 'lamb'): 3, ('groupB', 'cow'): 2, ('groupA', 'cow'): 1})
If you need a dict
:
>>> dict(Counter((k,v) for k in D for v in D[k]))
{('groupA', 'cow'): 1, ('groupB', 'cow'): 2, ('groupA', 'lamb'): 3}
or a list
:
>>> list(Counter((k,v) for k in D for v in D[k]).items())
[(('groupA', 'cow'), 1), (('groupB', 'cow'), 2), (('groupA', 'lamb'), 3)]
Upvotes: 2
Reputation: 353459
I think the canonical approach would be to use collections.Counter
:
>>> from collections import Counter
>>> d = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
>>> dc = {k: Counter(v) for k,v in d.items()}
>>> dc
{'groupA': Counter({'lamb': 3, 'cow': 1}), 'groupB': Counter({'cow': 2})}
after which you can access the nested counts:
>>> dc["groupA"]["lamb"]
3
Upvotes: 2
Reputation: 9868
Use the count
method on each list of animals:
farm = {"groupA":["cow","lamb","lamb","lamb"], "groupB":["cow","cow"]}
for group_name, animal_list in farm.items():
for animal in 'cow', 'lamb':
print(group_name, animal, animal_list.count(animal))
Upvotes: 0
Reputation: 83567
You can first count the number of each item in a list with a function something like this:
def countList(list):
counts = {}
for l in list:
if l in counts:
counts[l] += 1
else:
counts[l] = 1
return counts
Upvotes: 0