[Tutor] adding dictionary values

Kent Johnson kent37 at tds.net
Fri Mar 20 19:06:58 CET 2009


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

> if I want to do this with more than two dictionaries, the obvious solution
> for me is to use something like the reduce functions with a list of
> dictionary names like:
> dictList = [dict1, dict2, dict3]
> newDict = reduce(addDicts, dictList)
>
> Is this a satisfactory solution?

This will do some extra copying, as addDicts() always copies the first
argument. You would do better with something like
def addToDict(a, b):
   for k,v in b.iteritems():
       a[k] += v
   return a

newDict = reduce(addDictTo, dictList[1:], defaultdict(int, dictList[0]))

or rewrite addDicts() to take a variable number of arguments and loop
over the args.

Kent


More information about the Tutor mailing list