Betty
Betty

Reputation: 183

Searching and counting dictionary key value pairs

If I have a dictionary

dict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}

How do I

a) search for key substrings

b) sum the values of those selected

So I get the result:

('dog', 7) and ('cat', 10)

Upvotes: 2

Views: 117

Answers (4)

yourstruly
yourstruly

Reputation: 1002

With usage of dictionary for keeping subs:

dict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
subs={'dog':0,'cat':0}
for sub in subs.keys():
    for k,v in dict.items():
        if sub in k:
            subs[sub]+=v
print(subs)->{'dog': 7, 'cat': 10}

But if You want to guess subs keys automatically it may be harder xD!

Upvotes: 2

David S Jackson
David S Jackson

Reputation: 36

I'll take a crack at it, since I need the practice!

mydict = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
mykeys = ['dog', 'cat', 'rhino']
sums_dict = {}
for mkey in mykeys:
    for dkey in mydict.keys():
        if mkey in dkey:
            try:
                sums_dict[mkey] += mydict[dkey]
            except KeyError:
                sums_dict[mkey] = mydict[dkey]
print(sums_dict)

Upvotes: 0

gtlambert
gtlambert

Reputation: 11961

This is an alternative solution:

d = {'brown dogs':3, 'dog of white':4, 'white cats':1, 'white cat':9}
substrings = ['dog', 'cat']
my_list = [(substr, sum([d[key] for key in d.iterkeys() if substr in key])) for substr in substrings]
print my_list

Output

[('dog', 7), ('cat', 10)]

Upvotes: 1

Sait
Sait

Reputation: 19805

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()

for substring in substrings:
    for key in d:
        if substring in key:
            counter[substring] += d[key]

print(counter.items())

Output:

[('dog', 7), ('cat', 10)]

Upvotes: 3

Related Questions