[Python-ideas] dict.items to accept optional iterable with keys to use

Steven D'Aprano steve at pearwood.info
Wed Apr 4 10:23:01 CEST 2012

On Wed, Apr 04, 2012 at 11:07:55AM +0300, Victor Varvariuc wrote:
> Sometimes you want a dict which is subset of another dict. It would nice if
> dict.items accepted an optional list of keys to return. If no keys are
> given - use default behavior - get all items.

Too trivial to bother with.

# I want a list of keys/values:
items = [(key, mydict[key]) for key in list_of_keys]

# I want them generated on demand:
iterable = ((key, mydict[key]) for key in list_of_keys)

# I want a new dict:
newdict = dict((key, mydict[key]) for key in list_of_keys)

Both of those require that list_of_keys includes keys that do exist. If 
you want to skip missing keys:

[(k,v) for (k,v) in mydict.items() if k in list_of_keys]

To be even more efficient, use a set of keys instead of a list.


More information about the Python-ideas mailing list