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


当前回答

代码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略快一些。

其他回答

这是我的方法,支持嵌套字段,如mongo查询。

使用方法:

>>> obj = { "a":1, "b":{"c":2,"d":3}}
>>> only(obj,["a","b.c"])
{'a': 1, 'b': {'c': 2}}

只有函数:

def only(object,keys):
    obj = {}
    for path in keys:
        paths = path.split(".")
        rec=''
        origin = object
        target = obj
        for key in paths:
            rec += key
            if key in target:
                target = target[key]
                origin = origin[key]
                rec += '.'
                continue
            if key in origin:
                if rec == path:
                    target[key] = origin[key]
                else:
                    target[key] = {}
                target = target[key]
                origin = origin[key]
                rec += '.'
            else:
                target[key] = None
                break
    return obj

你可以使用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


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

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

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

如果你事先知道否定集(也不是键):

v = {'a': 'foo', 'b': 'bar', 'command': 'fizz', 'host': 'buzz'  }
args = {k: v[k] for k in v if k not in ["a", "b"]}
args # {'command': 'fizz', 'host': 'buzz'}

根据德尔南的回答。

如果你想要的钥匙不在旧字典里怎么办?delnan解决方案将抛出一个您可以捕获的KeyError异常。如果这不是你需要的,也许你想:

只包含同时存在于old_dict和你的wanted_keys集合中的键。 old_dict = {'name':"Foobar", 'baz':42} Wanted_keys = ['name', 'age'] New_dict = {k: old_dict[k] for k in set(wanted_keys) & set(old_dict.keys())} > > > new_dict {“名称”:“Foobar”} 对于old_dict中未设置的键具有默认值。 default =无 New_dict = {k: old_dict[k]如果k在old_dict否则默认k在wanted_keys} > > > new_dict {'age': None, 'name': 'Foobar'}