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


当前回答

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

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}

其他回答

下面是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的答案要慢。

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

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']

这个函数可以做到:

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

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

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

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()

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

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)