获取 Python 字典的子集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3953371/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:32:33  来源:igfitidea点击:

Get a sub-set of a Python dictionary

pythondictionary

提问by Oli

I have a dictionary:

我有一本字典:

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

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.

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

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}

回答by unutbu

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-comprehensiontoo:

在 Python3(或 Python2.7 或更高版本)中,您也可以使用dict-comprehension 来实现

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

回答by Bj?rn Pollex

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

回答by watsonic

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

在现代 Python (2.7+,3.0+) 中,使用字典理解:

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}

回答by Lei Zhao

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 ksis 0 or 1. The following code handles the situation and it is no longer an one-liner.

我不得不承认,上面的实现没有处理长度ks为 0 或 1 的情况。下面的代码处理这种情况,它不再是单行的。

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

回答by Nazime Lakehal

An other solution without if in dict comprehension.

没有 if in dict 理解的另一种解决方案。

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

回答by theo olsthoorn

With a complex class Myclassbeing 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 sublike so:

复杂类Myclasscollections.UserDict. 要选择它的一个子集,即保留其所有容器属性,定义一个方法很方便,例如命名sub如下:

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 ...])

然后用作Myclass.sub([key1, key2 ...])