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}
I have to admit though, the above implementation doesn't handle the case when the length of ks is 0 or 1. The following code handles the situation and it is no longer an one-liner.
With a complex class Myclass being a subclass of collections.UserDict. To select a subset of it, i.e keeping all its container properties, it's convenient to define a method, e.g. named sub like so:
def sub(self, keys):
subset = Myclass() # no arguments; works if defined with only keyword arguments
for key in keys:
subset[key] = self[key]
return subset