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


当前回答

下面是python 2.6中的一个例子:

>>> a = {1:1, 2:2, 3:3}
>>> dict((key,value) for key, value in a.iteritems() if key == 1)
{1: 1}

过滤部分是if语句。

如果你只想选择很多键中的几个,这个方法比delnan的答案要慢。

其他回答

这个函数可以做到:

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版本不同的是,该操作不是在适当的位置完成的,因此性能与字典中的键数有关。但是,这样做的好处是该函数不会修改所提供的字典。

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

这一行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对象输出。

另一个选择:

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()返回,而不是字典。

在我看来,这是最简单的方法:

d1 = {'a':1, 'b':2, 'c':3}
d2 = {k:v for k,v in d1.items() if k in ['a','c']}

我也喜欢这样做来揭示价值观:

a, c = {k:v for k,v in d1.items() if k in ['a','c']}.values()

这只是一个简单的单行函数,带有一个过滤器,只允许现有的键。

data = {'give': 'what', 'not': '___', 'me': 'I', 'no': '___', 'these': 'needed'}
keys = ['give', 'me', 'these', 'not_present']

n = { k: data[k] for k in filter(lambda k: k in data, keys) }

print(n)
print(list(n.keys()))
print(list(n.values()))

输出:

{“给予”:“什么”,“我”:“我”,“这些”:“需要”} ['give', 'me', 'these'] ['what', 'I', 'needed']