[Tutor] adding dictionary values

greg whittier greg at thewhittiers.com
Fri Mar 20 16:39:56 CET 2009


2009/3/20 Emad Nawfal (عماد نوفل) <emadnawfal at gmail.com>

> Hi Tutors,
> I have two pickled dictionaries containing word counts from two different
> corpora. I need to add the values, so that a word count is the sum of both.
> If the word "man" has a count of 2 in corpus A and a count of 3 in corpus B,
> then I need a new dictionary that  has "man": 5. Please let me know whether
> the following is correct/incorrect, good/bad, etc.
> Your help appreciated:
>
> def addDicts(a, b):
>     c = {}
>     for k in a:
>         if k not in b:
>             c[k] = a[k]
>         else:
>             c[k] = a[k] + b[k]
>
>     for k in b:
>         if k not in a:
>             c[k] = b[k]
>     return c
>
> # test this
> dict1 = {"dad": 3, "man": 2}
> dict2 = {"dad": 5, "woman": 10}
> newDict = addDicts(dict1, dict2)
> print(newDict)
> # This gives
>
> {'dad': 8, 'woman': 10, 'man': 2}
>
>
This looks like it will work, but you can accomplish this more compactly by
just looping over the items in both dictionaries and making use of the
default argument of the dictionaries get method.

newDict = {}
for k, v in dict1.items() + dict2.items():
    newDict[k] = newDict.get(k,0) + v
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090320/341387fc/attachment.htm>


More information about the Tutor mailing list