获取 Python 字典的一个子集

我有一本字典:

{'key1':1, 'key2':2, 'key3':3}

我需要将该字典的一个子集传递给第三方代码。它只想要一个包含键 ['key1', 'key2', 'key99']的字典,如果它得到另一个键(如 'key3') ,它就会爆炸成一团糟。有问题的代码不在我的控制范围之内,所以我必须清理我的字典。

最好的办法是什么,把字典限制在一串键上?

给定上面的示例字典和允许的键,我想要:

{'key1':1, 'key2':2}
84856 次浏览
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}
dict(filter(lambda i:i[0] in validkeys, d.items()))

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}

My way to do this is.

from operator import itemgetter


def subdict(d, ks):
return dict(zip(ks, itemgetter(*ks)(d)))


my_dict = {'key1':1, 'key2':2, 'key3':3}


subdict(my_dict, ['key1', 'key3'])

Update

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.

def subdict(d, ks):
vals = []
if len(ks) >= 1:
vals = itemgetter(*ks)(d)
if len(ks) == 1:
vals = [vals]
return dict(zip(ks, vals))

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}

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

It is then used as Myclass.sub([key1, key2 ...])

I see you like to keep the first 2 elements of the dict, so you can do:

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