2009/3/20 Emad Nawfal (ÚãÇÏ äæÝá) <span dir="ltr">&lt;<a href="mailto:emadnawfal@gmail.com">emadnawfal@gmail.com</a>&gt;</span><br><div class="gmail_quote"><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Hi Tutors,<br>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 &quot;man&quot; has a count of 2 in corpus A and a count of 3 in corpus B, then I need a new dictionary that  has &quot;man&quot;: 5. Please let me know whether the following is correct/incorrect, good/bad, etc.<br>

Your help appreciated:<br><br>def addDicts(a, b):<br>    c = {}<br>    for k in a:<br>        if k not in b:<br>            c[k] = a[k]<br>        else:<br>            c[k] = a[k] + b[k]<br>    <br>    for k in b:<br>        if k not in a:<br>

            c[k] = b[k]<br>    return c<br>    <br># test this<br>dict1 = {&quot;dad&quot;: 3, &quot;man&quot;: 2}<br>dict2 = {&quot;dad&quot;: 5, &quot;woman&quot;: 10}<br>newDict = addDicts(dict1, dict2)<br>print(newDict)<br>

# This gives<br><br>{&#39;dad&#39;: 8, &#39;woman&#39;: 10, &#39;man&#39;: 2}<br><font color="#888888"><br></font></blockquote><div><br>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.<br>
<br>newDict = {}<br>for k, v in dict1.items() + dict2.items():<br>    newDict[k] = newDict.get(k,0) + v<br><br><br></div></div><br>