I'm trying to write a function count(s, chars) that takes a string s and a list of characters chars. The function should count the number of occurrences of the letters given in chars. It should return a dictionary where the keys are the characters given in the list of characters chars.
So for example:
In [1]: s = "Another test string with x and y but no capital h." In [2]: count(s, ['A', 'a', 'z']) Out[2]: 'A': 1, 'a': 3, 'z': 0 I made some code that can count all the characters of the string and return a dictionary of it:
return {i: s.count(i) for i in set(s)} but I'm not sure how you would use a list of specific characters and return a dictionary...
{i: s.count(i) for i in l}wherelis the list of characters or{i: c[i] for i in l}wherec = collections.Counter(s).c.get(i,0)instead ofc[i]since it is possible the character did not occur in the string.0on missing items already @WillemVanOnsem, no need to usegethere :-)