Syntax for extracting multiple items from a dictionary
Peter Hansen
peter at engcorp.com
Wed Dec 1 12:39:07 EST 2004
Dave Merrill wrote:
> "anton muhin" wrote:
>>Or dict((key, row[key]) for key in cols).
>
> I'm on Py 2.3.3, and neither of these appear to work.
You're probably getting the error shown. Try the change in
the line following it instead.
Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]
>>> row = {'fname': 'Frank', 'lname': 'Jones', 'city': 'Hoboken',
'state': 'Alaska'}
>>> cols = ['city', 'state']
>>> dict((key, row[key]) for key in cols)
File "<stdin>", line 1
dict((key, row[key]) for key in cols)
^
SyntaxError: invalid syntax
>>> dict([(key, row[key]) for key in cols])
{'city': 'Hoboken', 'state': 'Alaska'}
> I can't see anything in the 2.4 release notes that point to where this would
> have changed.
See http://www.python.org/2.4/highlights.html and search for
"generator expressions".
-Peter
More information about the Python-list
mailing list