Python Cookbook dict problem
Steve Holden
sholden at holdenweb.com
Sat Aug 3 10:01:13 EDT 2002
"Aldo Cortesi" <aldo at nullcube.com> wrote in message
news:mailman.1028069393.17657.python-list at python.org...
> 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.
>
But
tada = dodict(yellow=2, green=4, **data)
would seem to be a more compact way of expressing the same idea. Does the
other example even work?
regards
-----------------------------------------------------------------------
Steve Holden http://www.holdenweb.com/
Python Web Programming http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------
More information about the Python-list
mailing list