So I have a dictionary
d = {'a': [4,'Adam', 2, ‘Bob’, 3], 'b': [3,'John', 4, ‘Bill’], 'c': [4,'Adam', 3, 4, ‘John’], 'd': [4,'Bill', ‘Joe’, 3], 'e': [4,'Bob', ‘Bob’, 5, 8, 10], 'f': [4, 'Joe'], 'g': [4, 'Bill', 4, ‘Joe’, 1]}
From which I want to return the counts of the names, such as
Adam: 2
Bill: 3
John: 2
Bob: 3
Joe: 3
I have tried using the collections counter through this function:
x = 0
for vals in d.itervalues():
while x<len(vals):
if type(vals[x]) == str:
print Counter([vals[x]])
x = x+1
Which returns
Counter({'Adam': 1})
Counter({'Bob': 1})
Counter({'Adam': 1})
Counter({'John': 1})
Counter({'John': 1})
Counter({'Bill': 1})
Counter({'Bob': 1})
Counter({'Bob': 1})
Counter({'Bill': 1})
Counter({'Joe': 1})
Counter({'Bill': 1})
Counter({'Joe': 1})
Counter({'Joe': 1})
But that isn’t the result I want. Would I just need to add the counters? How would I do that? I know the counter class has an add/ subtract function but the methods I’m trying aren’t working.
I’ve also tried something like this to print out different counters for each variation.
'c%s'%(x)
Which would set c1, c2, c3 for each counter and then I could just add them with c1 + c2 + c3 to get the result I want. However, I am unable to print these different counter lists out.
Along with that, once it does return a result, it always returns “Counter({__})”. How would I go about deleting that portion or just printing out the names and count solely?
Thanks for the help!
You are creating a new
Counterinstance for each item you are counting, where you need a single instance to count them all:This results in
Note that you should generally avoid the kind of heterogeneous lists that occurs in your dictionary values if possible.