Python 返回不包括指定键的字典副本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31433989/
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
Return copy of dictionary excluding specified keys
提问by Juicy
I want to make a function that returns a copy of a dictionary excluding keys specified in a list.
我想创建一个函数,该函数返回字典的副本,不包括列表中指定的键。
Considering this dictionary:
考虑到这本词典:
my_dict = {
"keyA": 1,
"keyB": 2,
"keyC": 3
}
A call to without_keys(my_dict, ['keyB', 'keyC'])
should return:
调用without_keys(my_dict, ['keyB', 'keyC'])
应该返回:
{
"keyA": 1
}
I would like to do this in a one-line with a neat dictionary comprehension but I'm having trouble. My attempt is this:
我想用简洁的字典理解在一行中做到这一点,但我遇到了麻烦。我的尝试是这样的:
def without_keys(d, keys):
return {k: d[f] if k not in keys for f in d}
which is invalid syntax. How can I do this?
这是无效的语法。我怎样才能做到这一点?
采纳答案by u1860929
You were close, try the snippet below:
你很接近,试试下面的片段:
>>> my_dict = {
... "keyA": 1,
... "keyB": 2,
... "keyC": 3
... }
>>> invalid = {"keyA", "keyB"}
>>> def without_keys(d, keys):
... return {x: d[x] for x in d if x not in keys}
>>> without_keys(my_dict, invalid)
{'keyC': 3}
Basically, the if k not in keys
will go at the end of the dict comprehension in the above case.
基本上,if k not in keys
在上述情况下,将出现在 dict 理解的末尾。
回答by Morgan Thrapp
This should work for you.
这应该对你有用。
def without_keys(d, keys):
return {k: v for k, v in d.items() if k not in keys}
回答by Anand S Kumar
In your dictionary comprehension you should be iterating over your dictionary (not k
, not sure what that is either). Example -
在您的字典理解中,您应该迭代您的字典(不是k
,也不确定那是什么)。例子 -
return {k:v for k,v in d.items() if k not in keys}
回答by Himel Das
For those who don't like list comprehensions, this is my version:
对于那些不喜欢列表推导式的人,这是我的版本:
def without_keys(d, *keys):
return dict(filter(lambda key_value: key_value[0] not in keys, d.items()))
Usage:
用法:
>>> d={1:3, 5:7, 9:11, 13:15}
>>> without_keys(d, 1, 5, 9)
{13: 15}
>>> without_keys(d, 13)
{1: 3, 5: 7, 9: 11}
>>> without_keys(d, *[5, 7])
{1: 3, 13: 15, 9: 11}
回答by Kasramvd
I think simple is better than complex and in this case the Pythoic way would be to pop the unwanted items from your dictionary because filtering will almost always requires a loop on a subset of all items (the cost of popping and membership checking is almost negligible because of the hashing).
我认为简单总比复杂好,在这种情况下,Pythoic 方法是从字典中弹出不需要的项目,因为过滤几乎总是需要对所有项目的一个子集进行循环(弹出和成员资格检查的成本几乎可以忽略不计,因为的散列)。
def without_keys(d, ex):
for i in ex: d.pop(i)
return d
Demo:
演示:
In [11]: my_dict = {
...: "keyA": 1,
...: "keyB": 2,
...: "keyC": 3
...: }
In [12]:
In [12]: def without_keys(d, ex):
...: for i in ex: d.pop(i)
...: return d
...:
In [13]: without_keys(my_dict, ['keyB', 'keyC'])
Out[13]: {'keyA': 1}