Syntax for extracting multiple items from a dictionary

Jean Brouwers mrjean1ATcomcastDOTnet at no.spam.net
Wed Dec 1 16:49:39 CET 2004


The correct syntax is:

    dict([(key, row[key]) for key in cols])

i.e. the list must be enclosed in [...].

/Jean Brouwers



In article <7OednTjJLOltfDDcRVn-og at rcn.net>, Dave Merrill
<dmerrillq at usaq.netq> wrote:

> "anton muhin" wrote:
> > Stefan Behnel wrote:
> > >
> > >
> > > shark schrieb:
> > >
> > >> row = {"fname" : "Frank", "lname" : "Jones", "city" : "Hoboken",
> > >> "state" :
> > >> "Alaska"}
> > >> cols = ("city", "state")
> > >>
> > >> Is there a best-practices way to ask for an object containing only the
> > >> keys
> > >> named in cols out of row? In other words, to get this:
> > >> {"city" : "Hoboken", "state" : "Alaska"}
> > >
> > >
> > > Untested:
> > >
> > > dict( (key,value) for (key,value) in row.iteritems() if key in cols )
> > >
> > > Works in Py2.4
> > >
> > > Stefan
> >
> > Or dict((key, row[key]) for key in cols).
> >
> > regards,
> > anton.
> 
> I'm on Py 2.3.3, and neither of these appear to work. Can someone confirm? I
> can't see anything in the 2.4 release notes that point to where this would
> have changed.
> 
> Thanks,
> 
> shark
> 
>



More information about the Python-list mailing list