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 -

dns - Dokku server hosts two sites with TLD's, both domains are landing on only one app -

Delphi 7 and decode UTF-8 base64 -