user2578185
user2578185

Reputation: 437

How to add in a dictionary the values that have similar keys?

I would like to add together the values from a dictionary in Python, if their keys begin with the same letter..

For example, if I have this dictionary: {'apples': 3, 'oranges': 5, 'grapes': 4, 'apricots': 2, 'grapefruit': 9}

The result would be: {'A': 5,'G': 13, 'O': 5}

I only got this far and I'm stuck:

for k in dic.keys():
  if k.startswith('A'):

Any help will be appreciated

Upvotes: 1

Views: 95

Answers (3)

Duncan
Duncan

Reputation: 95722

Lots of ways to do this. Here's a variant using Counter that nobody else has suggested and unlike Ashwini's solution it doesn't create potentially long intermediate strings:

>>> from collections import Counter
>>> dic = {'apples': 3, 'oranges': 5, 'grapes': 4, 'apricots': 2, 'grapefruit': 9}
>>> sum((Counter({k[0].upper():dic[k]}) for k in dic), Counter())
Counter({'G': 13, 'A': 5, 'O': 5})

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1124100

Take the first character of each key, call .upper() on that and sum your values by that uppercased letter. The following loop

out = {}
for key, value in original.iteritems():
    out[key[0].upper()] = out.get(key[0].upper(), 0) + value

should do it.

You can also use a collections.defaultdict() object to simplify that a little:

from collections import defaultdict:

out = defaultdict(int)
for key, value in original.iteritems():
    out[key[0].upper()] += value

or you could use itertools.groupby():

from itertools import groupby

key = lambda i: i[0][0].upper()
out = {key: sum(v for k, v in group) for key, group in groupby(sorted(original.items(), key=key), key=key)}

Upvotes: 3

TerryA
TerryA

Reputation: 60014

You can use a defaultdict here:

from collections import defaultdict
new_d = defaultdict(int)
for k, v in d.iteritems():
    new_d[k[0].upper()] += v

print new_d

Prints:

defaultdict(<type 'int'>, {'A': 5, 'O': 5, 'G': 13})

Upvotes: 2

Related Questions