Python Cookbook dict problem
Aldo Cortesi
aldo at nullcube.com
Tue Jul 30 18:44:27 EDT 2002
Thus spake Dave Reed (dreed at capital.edu):
>
> I'm trying the following Python Cookbook recipe with python2.2
>
>
> def makedict(**kwargs):
> return kwargs
> data = makedict(red=1, green=2, blue=3)
> def dodict(*args, **kwds):
> d = {}
> for k, v in args: d[k] = v
> d.update(kwds)
> return d
> tada = dodict(*data.items(), yellow=2, green=4)
>
>
> but I get an error with the last line:
> >>> tada = dodict(*data.items(), yellow=2, green=4)
> File "<stdin>", line 1
> tada = dodict(*data.items(), yellow=2, green=4)
> ^
> SyntaxError: invalid syntax
>
> What's wrong?
Dave,
Python expects you to do positional and keyword argument
unrolling at the end of the function argument list (i.e.
after all "normal" arguments). Change the last line to:
tada = dodict(yellow=2, green=4, *data.items())
and Bob should be your metaphorical uncle.
Aldo
--
Aldo Cortesi
aldo at nullcube.com
More information about the Python-list
mailing list