[Tutor] Objectifying code
Stephan Richter
stephan.richter@tufts.edu
Fri Feb 7 20:48:45 2003
On Tuesday 04 February 2003 02:15, Magnus Lycka wrote:
> At 10:47 2003-02-04 +0630, John Abbe wrote:
> >Hm, my Python says "TypeError: unsupported operand types for +: 'dict' and
> >'dict'"
>
> Mine too. How silly of me! "When in doubt, refuse the temptation
> to guess." I should have known that Python would refuse to do
> something unclearly defined like that. The problem is what to do
> when you run into the same key in both dicts.
>
> Of course your approach works.
>
> I guess I should have done:
>
> import copy
> stringFields = copy.copy(entry)
> stringFields['cgiaddr'] = cgiaddr
> print x % stringFields
>
> Or, for a more generic (simply overwriting) merge
>
> >>> def dictMerge(*dicts):
>
> ... all = {}
> ... for dict in dicts:
> ... for key, value in dict.items():
> ... all[key] = value
> ... return all
> ...
>
> >>> print dictMerge({1:2,2:3},{2:4,3:4},{'a':'b'})
Shrug, what about dict1.update(dict2)? This function is fast, since it is
written in C.
Regards,
Stephan
--
Stephan Richter
CBU Physics & Chemistry (B.S.) / Tufts Physics (Ph.D. student)
Web2k - Web Software Design, Development and Training