python - Searching and counting dictionary key value pairs -
if have dictionary
dict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
how
a) search key substrings
b) sum values of selected
so result:
('dog', 7) , ('cat', 10)
you can use collections.counter
.
from collections import counter d = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9} substrings = ['dog', 'cat'] counter = counter() substring in substrings: key in d: if substring in key: counter[substring] += d[key] print(counter.items())
output:
[('dog', 7), ('cat', 10)]
Comments
Post a Comment