[Tutor] adding dictionary values

Emad Nawfal (عماد نوفل) emadnawfal at gmail.com
Sat Mar 21 10:46:43 CET 2009


2009/3/20 Kent Johnson <kent37 at tds.net>

> 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
>
Thanks Kent and All. I appreciate your helpfulness


-- 
لا أعرف مظلوما تواطأ الناس علي هضمه ولا زهدوا في إنصافه كالحقيقة.....محمد
الغزالي
"No victim has ever been more repressed and alienated than the truth"

Emad Soliman Nawfal
Indiana University, Bloomington
--------------------------------------------------------
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090321/942c3ab9/attachment.htm>


More information about the Tutor mailing list