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

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -