Subsetting a dictionary

Will Newton will at nospam.misconception.org.uk
Mon Mar 19 19:10:45 CET 2001


Terry Reedy wrote:

> Hmmm.  What you need is a currently imaginary feature that we might call a
> dict comprehension,
> with syntax paralleling that for list comprehensions:
> D2 = {key:val for (key,val) in D if constraint(key,val)}
 
That would indeed be cool. The worry I have with this syntax is the 
constraint will often be on only the value or the key (as in my case) and 
accessing the dict as a list of key-value tuples may be very slow and not 
much faster than the current way of doing things. (And why not use a list 
of tuples in this case?)

I'm not sure exactly how it would be best do this, but I think it could be 
a useful feature.





More information about the Python-list mailing list