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


当前回答

我们可以这样简单地处理函数:

>>> dict_filter = lambda x, y: dict([ (i,x[i]) for i in x if i in set(y) ])
>>> large_dict = {"a":1,"b":2,"c":3,"d":4}
>>> new_dict_keys = ("c","d")
>>> small_dict=dict_filter(large_dict, new_dict_keys)
>>> print(small_dict)
{'c': 3, 'd': 4}
>>> 

其他回答

你可以使用python-benedict,它是dict的子类。

安装:pip install python-benedict

from benedict import benedict

dict_you_want = benedict(your_dict).subset(keys=['firstname', 'lastname', 'email'])

它在GitHub上开源:https://github.com/fabiocaccamo/python-benedict


声明:我是这个库的作者。

这个函数可以做到:

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

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

你可以用我的函数库中的项目函数来做:

from funcy import project
small_dict = project(big_dict, keys)

还要看一下select_keys。

给定你的原始字典orig和你感兴趣的键的条目集:

filtered = dict(zip(keys, [orig[k] for k in keys]))

这并不像delnan的答案那么好,但应该适用于每个感兴趣的Python版本。然而,它对原始字典中存在的每个键元素都是脆弱的。

代码1:

dict = { key: key * 10 for key in range(0, 100) }
d1 = {}
for key, value in dict.items():
    if key % 2 == 0:
        d1[key] = value

代码2:

dict = { key: key * 10 for key in range(0, 100) }
d2 = {key: value for key, value in dict.items() if key % 2 == 0}

代码3:

dict = { key: key * 10 for key in range(0, 100) }
d3 = { key: dict[key] for key in dict.keys() if key % 2 == 0}

所有代码段的性能都用timeit度量,使用number=1000,并为每段代码收集1000次。

对于python 3.6,三种过滤字典键的方式的性能几乎相同。对于python 2.7,代码3略快一些。