[Tutor] adding dictionary values

Kent Johnson kent37 at tds.net
Fri Mar 20 17:00:12 CET 2009


2009/3/20 greg whittier <greg at thewhittiers.com>:

> 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

Even simpler, start with a copy of dict1:
newDict = dict(dict1)
for k, v in dict2.items():
    newDict[k] = newDict.get(k,0) + v

Kent


More information about the Tutor mailing list