Python: 从dict字典中删除键的不同方法 del vs dict.pop(), Different ways to Remove a key from Dictionary in Python | del vs dict.pop()

 

在本文中,我们将讨论从python中的字典中删除键的不同方法。

假设我们有一个字符串和整数的字典,即

# Dictionary of strings and int
wordFreqDic = {
"Hello": 56,
"at" : 23 ,
"test" : 43,
"this" : 43
}

现在我们要从字典中删除键为“ at”的项目。让我们看看如何做到这一点,

 

使用del从字典中删除键

del d[key]

del语句从字典中删除给定的项目。如果字典中不存在给定的键,则它将抛出KeyError。

让我们用它从上述字典中删除密钥,

''' 
Deleting an entry from dictionary using del 
'''
# If key exist in dictionary then delete it using del.
if "at" in wordFreqDic:
    del wordFreqDic["at"]
    
print("Updated Dictionary :" , wordFreqDic)

输出:

''' 
Deleting an entry from dictionary using del and try/except  
'''
# If key is not present in dictionary, then del can throw KeyError
try:
    del wordFreqDic["testing"]
except KeyError:
    print("Key 'testing' not found")

输出:

Key 'testing' not found

 

使用dict.pop()从字典中删除键

让我们使用pop()删除字典中不存在的元素

# Trying to delete an element from dict, which is not present.
# It will return given default value i.e. None     
result = wordFreqDic.pop("testing", None)    
 
print("Deleted item's value = ", result)
print("Updated Dictionary :" , wordFreqDic)

 

输出:

Deleted item's value = None
Updated Dictionary : {'Hello': 56, 'test': 43}

它将返回给定的默认值,即无

pop()的默认值是必需的,因为如果字典中不存在给定的键,而pop()中没有给定的默认值,则它将抛出keyError。

 

使用pop()和try / except从字典中删除密钥

让我们使用pop()删除字典中不存在的元素,并且不通过pop()传递默认值参数,即

# Trying to delete an element from dict, which is not present.
# Also, if we don't pass any default value then it will throw KeyError.     
 
try:
    wordFreqDic.pop("testing")    
except KeyError:
    print("Key not found")

 

输出:

本文: Python: 从dict字典中删除键的不同方法 del vs dict.pop(), Different ways to Remove a key from Dictionary in Python | del vs dict.pop()

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.