[Python-ideas] Add a method to get the subset of a dictionnary.

Terry Reedy tjreedy at udel.edu
Wed Oct 12 17:52:30 EDT 2016


On 10/12/2016 12:06 PM, Enguerrand Pelletier wrote:
> Hi all,
>
> It always bothered me to write something like this when i want to strip
> keys from a dictionnary in Python:
>
> a = {"foo": 1, "bar": 2, "baz": 3, "foobar": 42}
> interesting_keys = ["foo", "bar", "baz"]

If the keys are hashable, this should be a set.

> b = {k, v for k,v in a.items() if k in interesting_keys}

Test code before posting.  The above is a set comprehension creating a 
set of tupes.  For a dict, 'k, v' must be 'k:v'.

> Wouldn't it be nice to have a syntactic sugar such as:
>
> b = a.subset(interesting_keys)

It is pretty rare for the filter condition to be exactly 'key in 
explicit_keys'.  If it is, one can directly construct the dict from a 
and explict_keys.

b = {k:a[k] for k in interesting_keys}

The syntactic sugar wrapping this would save 6 keypresses. 
Interesting_keys can be any iterable.  To guarantee no KeyErrors, add 
'if k in a'.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list