Reputation: 909
Trying to count how many times a value from a list appears in another list. In the case of:
my_list = [4,4,4,4,4,4,5,8]
count_items = [4,5,8]
this works fine:
from collections import Counter
print (Counter(my_list))
>> Counter({4: 6, 5: 1, 8: 1})
However, if my_list does not have any entries for '4', for example
my_list = [5,8]
count_items = [4,5,8]
print (Counter(my_list))
>> Counter({5: 1, 8: 1})
While I am looking for this output:
>> Counter({4: 0, 5: 1, , 8: 1})
Upvotes: 0
Views: 82
Reputation: 362488
A counter is a dict and implements the update method, which preserves zeros:
>>> counter = Counter(my_list)
>>> counter
Counter({5: 1, 8: 1})
>>> counter.update(dict.fromkeys(count_items, 0))
>>> counter
Counter({5: 1, 8: 1, 4: 0})
Upvotes: 0
Reputation: 154
Counter
has no way to know that you would expect 4s to be counted, so by default only accounts for elements it finds in the list. An alternative approach would be:
my_list = [5,8]
count_items = [4,5,8]
counter = {i: sum(map(lambda x: 1 if x == i else 0, my_list)) for i in count_items}
print (counter)
>> {4: 0, 5: 1, 8: 1}
Upvotes: 0
Reputation: 188
What do you need the value for?
Because the counter you have here actually returns 0 when asked for the key 4:
my_list = [5,8]
count_items = [4,5,8]
counter = Counter(my_list)
print(counter)
>> Counter({5: 1, 8: 1})
print(counter[4])
>> 0
Upvotes: 1