Get a sub-set of a Python dictionary

Solution 1:

In [38]: adict={'key1':1, 'key2':2, 'key3':3}
In [41]: dict((k,adict[k]) for k in ('key1','key2','key99') if k in adict)
Out[41]: {'key1': 1, 'key2': 2}

In Python3 (or Python2.7 or later) you can do it with a dict-comprehension too:

>>> {k:adict[k] for k in ('key1','key2','key99') if k in adict}
{'key2': 2, 'key1': 1}

Solution 2:

dict(filter(lambda i:i[0] in validkeys, d.iteritems()))

Solution 3:

In modern Python (2.7+,3.0+), use a dictionary comprehension:

d = {'key1':1, 'key2':2, 'key3':3}
included_keys = ['key1', 'key2', 'key99']

{k:v for k,v in d.items() if k in included_keys}

Solution 4:

An other solution without if in dict comprehension.

>>> a = {'key1':1, 'key2':2, 'key3':3}
>>> b = {'key1':1, 'key2':2}
>>> { k:a[k] for k in b.keys()}
{'key2': 2, 'key1': 1}