获取Python词典的子集 [英] Get a sub-set of a Python dictionary
问题描述
我有字典:
{'key1':1, 'key2':2, 'key3':3}
我需要将该词典的子集传递给第三方代码.它只需要一个包含键 ['key1','key2','key99']
的字典,如果它得到另一个键(例如'key3'
),它就会爆炸一团糟.有问题的代码不在我的控制范围内,所以我必须清理字典.
I need to pass a sub-set of that dictionary to third-party code. It only wants a dictionary containing keys ['key1', 'key2', 'key99']
and if it gets another key (eg 'key3'
), it explodes in a nasty mess. The code in question is out of my control so I'm left in a position where I have to clean my dictionary.
将字典限制为一组键的最佳方法是什么?
What's the best, way to limit a dictionary to a set of keys?
鉴于示例字典和上面允许的键,我想要:
Given the example dictionary and allowed keys above, I want:
{'key1':1, 'key2':2}
推荐答案
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}
在Python3(或Python2.7或更高版本)中,您可以使用 dict-comprehension dict-comprehension 也是:
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}
这篇关于获取Python词典的子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!