我有一个字典,里面有一大堆词条。我只对其中的几个感兴趣。有什么简单的方法可以把其他的都剪掉吗?


当前回答

另一个选择:

content = dict(k1='foo', k2='nope', k3='bar')
selection = ['k1', 'k3']
filtered = filter(lambda i: i[0] in selection, content.items())

但你得到的是一个列表(Python 2)或一个迭代器(Python 3),由filter()返回,而不是字典。

其他回答

略为优雅的词典理解:

foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}

这一行lambda应该工作:

dictfilt = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])

这里有一个例子:

my_dict = {"a":1,"b":2,"c":3,"d":4}
wanted_keys = ("c","d")

# run it
In [10]: dictfilt(my_dict, wanted_keys)
Out[10]: {'c': 3, 'd': 4}

它是一个基本的列表推导式,遍历你的dict键(i in x),如果键位于你想要的键列表(y)中,则输出一个元组(键,值)对列表。dict()将整个内容包装成dict对象输出。

这个函数可以做到:

def include_keys(dictionary, keys):
    """Filters a dict by only including certain keys."""
    key_set = set(keys) & set(dictionary.keys())
    return {key: dictionary[key] for key in key_set}

就像delnan的版本一样,这个版本使用字典理解,并且对于大型字典具有稳定的性能(仅取决于您允许的键数,而不是字典中的键总数)。

就像MyGGan的版本一样,这个版本允许您的键列表包含字典中可能不存在的键。

作为奖励,这里是反向的,在这里你可以通过排除原始的某些键来创建字典:

def exclude_keys(dictionary, keys):
    """Filters a dict by excluding certain keys."""
    key_set = set(dictionary.keys()) - set(keys)
    return {key: dictionary[key] for key in key_set}

注意,与delnan版本不同的是,该操作不是在适当的位置完成的,因此性能与字典中的键数有关。但是,这样做的好处是该函数不会修改所提供的字典。

编辑:添加了一个单独的功能,用于从字典中排除某些键。

如果我们想要创建一个删除选定键的新字典,我们可以使用字典理解 例如:

d = {
'a' : 1,
'b' : 2,
'c' : 3
}
x = {key:d[key] for key in d.keys() - {'c', 'e'}} # Python 3
y = {key:d[key] for key in set(d.keys()) - {'c', 'e'}} # Python 2.*
# x is {'a': 1, 'b': 2}
# y is {'a': 1, 'b': 2}

我们也可以通过稍微更优雅的字典理解来实现这一点:

my_dict = {"a":1,"b":2,"c":3,"d":4}

filtdict = {k: v for k, v in my_dict.items() if k.startswith('a')}
print(filtdict)