从 Python 中的字典中删除键返回新字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17665809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove key from dictionary in Python returning new dictionary
提问by Xeos
I have a dictionary
我有字典
d = {'a':1, 'b':2, 'c':3}
I need to remove a key, say cand return the dictionary without that key in one function call
我需要删除一个键,比如c并在一个函数调用中返回没有该键的字典
{'a':1, 'b':2}
d.pop('c') will return the key value - 3 - instead of the dictionary.
d.pop('c') 将返回键值 - 3 - 而不是字典。
I am going to need one function solution if it exists, as this will go into comprehensions
如果存在,我将需要一个函数解决方案,因为这将进入理解
采纳答案by jh314
How about this:
这个怎么样:
{i:d[i] for i in d if i!='c'}
It's called Dictionary Comprehensionsand it's available since Python 2.7.
它被称为Dictionary Comprehensions,它从 Python 2.7 开始可用。
or if you are using Python older than 2.7:
或者如果您使用的 Python 版本早于 2.7:
dict((i,d[i]) for i in d if i!='c')
回答by Gustav Larsson
Why not roll your own? This will likely be faster than creating a new one using dictionary comprehensions:
为什么不自己动手?这可能比使用字典推导式创建一个新的更快:
def without(d, key):
new_d = d.copy()
new_d.pop(key)
return new_d
回答by sinaiy
this will work,
这会起作用,
(lambda dict_,key_:dict_.pop(key_,True) and dict_)({1:1},1)
EDIT this will drop the key if exist in the dictionary and will return the dictionary without the key,value pair
编辑这将删除字典中存在的键,并将返回没有键值对的字典
in python there are functions that alter an object in place, and returns a value instead of the altered object, {}.pop function is an example.
在 python 中,有一些函数可以改变对象,并返回一个值而不是改变的对象,{}.pop 函数就是一个例子。
we can use a lambda function as in the example, or more generic below (lambda func:obj:(func(obj) and False) or obj) to alter this behavior, and get a the expected behavior.
我们可以使用示例中的 lambda 函数,或更通用的下面(lambda func:obj:(func(obj) and False) 或 obj) 来改变此行为,并获得预期的行为。
回答by Felix Yuan
>>> a = {'foo': 1, 'bar': 2}
>>> b = a.pop('foo'); a
{'bar': 2}
回答by z0r
If you need an expressionthat does this (so you can use it in a lambda or comprehension) then you can use this little hacktrick: create a tuple with the dictionary and the popped element, and then get the original item back out of the tuple:
如果你需要一个表达,这是否(所以你可以在lambda和理解使用它),那么你可以使用这个小黑客伎俩:创建一个字典和弹出的元素的元组,然后让原来的项背出来的元组:
(foo, foo.pop(x))[0]
For example:
例如:
ds = [{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]
[(d, d.pop('c'))[0] for d in ds]
assert ds == [{'a': 1, 'b': 2}, {'a': 4, 'b': 5}]
Note that this actually modifies the original dictionary, so despite being a comprehension, it's not purely functional.
请注意,这实际上修改了原始字典,因此尽管是一种理解,但它并不是纯粹的功能。