Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/visual-studio-2012/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从Python字典中删除密钥?_Python_Dictionary_Data Structures_Unset - Fatal编程技术网

如何从Python字典中删除密钥?

如何从Python字典中删除密钥?,python,dictionary,data-structures,unset,Python,Dictionary,Data Structures,Unset,从字典中删除密钥时,我使用: if 'key' in my_dict: del my_dict['key'] 是否有一种单行方式来执行此操作?要删除键,无论它是否在字典中,请使用以下两种参数形式: if 'key' in my_dict: del my_dict['key'] my_dict.pop('key',None) 如果字典中存在key,则返回my_dict[key],否则返回None。如果未指定第二个参数(即my dict.pop('key'))且key不存在,则会引发k

从字典中删除密钥时,我使用:

if 'key' in my_dict:
    del my_dict['key']

是否有一种单行方式来执行此操作?

要删除键,无论它是否在字典中,请使用以下两种参数形式:

if 'key' in my_dict: del my_dict['key']
my_dict.pop('key',None)
如果字典中存在
key
,则返回
my_dict[key]
,否则返回
None
。如果未指定第二个参数(即
my dict.pop('key')
)且
key
不存在,则会引发
key错误

要删除保证存在的密钥,还可以使用

del my_dict['key']
如果该键不在字典中,这将引发一个
KeyError

特别是要回答“是否有一种单行的方法可以这样做?”

a={9:4,2:3,4:2,1:3}
a.pop(9)
print(a)
…好吧,你问;-)

您应该考虑,从<代码> DIST</代码>中删除对象的方法是:<代码>键“< /代码>可能在<代码> MyOutDist</代码>期间< <代码> >语句,但可以在<代码> del < /C>执行之前删除,在这种情况下,代码> del < /代码>将以<代码> KeyError < /代码>失败。考虑到这一点,最安全的做法是按照

try:
    del my_dict['key']
except KeyError:
    pass

当然,这绝对不是一行。

我花了一些时间才弄清楚我的dict.pop(“key”,None)到底在做什么。因此,我将添加以下内容作为一个答案,以节省其他人的谷歌搜索时间:

pop(键[,默认])
如果键在字典中,请删除它并返回其值,否则 返回默认值。如果未给出默认值且密钥不在 字典中,将引发一个
KeyError


如果您需要在一行代码中删除字典中的许多键,我认为使用map()非常简洁易懂:

myDict = {'a':1,'b':2,'c':3,'d':4}
map(myDict.pop, ['a','c']) # The list of keys to remove
>>> myDict
{'b': 2, 'd': 4}
如果需要捕获弹出字典中没有的值的错误,请使用lambda inside map()如下所示:

map(lambda x: myDict.pop(x,None), ['a', 'c', 'e'])
[1, 3, None] # pop returns
>>> myDict
{'b': 2, 'd': 4}
或者在
python3
中,必须使用列表理解:

[myDict.pop(x, None) for x in ['a', 'c', 'e']]
它起作用了。即使myDict没有“e”键,“e”也不会导致错误。

您可以使用创建一个新的字典,并删除该键:

>>> my_dict = {k: v for k, v in my_dict.items() if k != 'key'}

您可以按条件删除。如果
键不存在,则不会出错。

删除我的dict[key]
我的dict.pop(key)
在键存在时从字典中删除键的速度稍快

>>> import timeit
>>> setup = "d = {i: i for i in range(100000)}"

>>> timeit.timeit("del d[3]", setup=setup, number=1)
1.79e-06
>>> timeit.timeit("d.pop(3)", setup=setup, number=1)
2.09e-06
>>> timeit.timeit("d2 = {key: val for key, val in d.items() if key != 3}", setup=setup, number=1)
0.00786
my_dict.pop('key', None)
但是当密钥不存在时
如果my_dict:del my_dict[key]
中的密钥比
my_dict.pop(key,None)
稍快。在
try
/
语句中,这两种方法的速度至少是
del
的三倍,但
语句除外:

>>> timeit.timeit("if 'missing key' in d: del d['missing key']", setup=setup)
0.0229
>>> timeit.timeit("d.pop('missing key', None)", setup=setup)
0.0426
>>> try_except = """
... try:
...     del d['missing key']
... except KeyError:
...     pass
... """
>>> timeit.timeit(try_except, setup=setup)
0.133
使用“del”关键字:


我们可以通过以下方法从Python字典中删除密钥

使用
del
关键字;这几乎和你做的一样-

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

我们可以这样做:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100
但是我们应该记住,在这个过程中,实际上它不会从字典中删除任何键,而不是从字典中排除特定键。此外,我注意到它返回的字典顺序与myDict的顺序不同

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}
如果我们在shell中运行它,它将执行类似于
{'five':500,'four':400,'three':300,'two':200}
-请注意,它的顺序与
myDict
不同。同样,如果我们尝试打印
myDict
,那么我们可以看到所有键,包括通过这种方法从字典中排除的键。但是,我们可以通过将以下语句赋给变量来创建新字典:

var = {key:value for key, value in myDict.items() if key != 'one'}
现在,如果我们尝试打印它,那么它将遵循父级顺序:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

使用
pop()
方法

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}
del
pop
之间的区别在于,使用
pop()
方法,如果需要,我们实际上可以存储键的值,如下所示:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

Fork供将来参考,如果您觉得这很有用。

如果您希望非常详细,可以使用异常处理:

try: 
    del dict[key]

except KeyError: pass
但是,如果密钥不存在,则这比
pop()
方法要慢

my_dict.pop('key', None)
对于几个键来说,这并不重要,但是如果您反复这样做,那么后一种方法是更好的选择

最快的方法是:

if 'key' in dict: 
    del myDict['key']

但是这种方法是危险的,因为如果在两行之间删除
'key'
,将引发
keyrorm

我更喜欢不可变版本

foo={
1:1,
2:2,
3:3
}
removeKeys=[1,2]
def woKeys(dct、keyIter):
返回{
k:v
对于k,如果k不在keyIter中,则dct.items()中的v
}
>>>打印(woKeys(foo,removeKeys))
{3: 3}
>>>打印(foo)
{1: 1, 2: 2, 3: 3}

另一种方法是使用items()+听写理解

items()与dict理解相结合也可以帮助我们完成删除键值对的任务,但它有一个缺点,即它不是一种就地dict技术。实际上,如果创建了一个新的dict,除了我们不希望包含的键之外

test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}

# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}

# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))
输出:

dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}
键上的单过滤器
  • 如果my_dict中存在“key”,则返回“key”并将其从my_dict中删除
  • 如果my_dict中不存在“key”,则返回None
这将在适当位置更改我的指令(可变)

my_dict.pop('key',None)
关键点上的多个过滤器 生成新的dict(不可变)

dic1={
“x”:1,
“y”:2,
“z”:3
}
def func1(项目):
退货项目[0]!=“x”和项目[0]!=“y”
印刷品(
口述(
滤器(
lambda项目:项目[0]!=“x”和项目[0]!=“y”,
dic1.项目()
)
)
)

字典数据类型有一个名为
dict_name.pop(item)
的方法,可用于从字典中删除键:值对

a={9:4,2:3,4:2,1:3}
a.pop(9)
print(a)
这将给出如下输出:

{2: 3, 4: 2, 1: 3}
这样您就可以删除一个站点