Validus A dead simple Python data validation library.…
October 11, 2019
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)
输出:
Updated Dictionary : {'Hello': 56, 'test': 43, 'this': 43}
有必要在删除之前检查字典中是否存在密钥,否则请使用throw keyError删除del。
使用del和try / except从字典中删除密钥
如果我们不想在调用del之前添加if if检查,我们也可以使用try / except。让我们尝试删除字典中不存在的键并捕获错误,即
''' 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()从字典中删除键
dict.pop(key[, default])
- 如果字典中存在键,则dict.pop()从字典中删除具有给定键的元素并返回其值。
- 如果字典中不存在给定的键,则它将返回给定的默认值。
- 如果字典中不存在给定键,并且没有将默认值传递给pop(),它将抛出KeyError
让我们使用pop()从dict中删除一个元素
''' Deleting an entry from dictionary using pop() ''' # As 'this' key is present in dict, so pop() will delete its entry and return its value result = wordFreqDic.pop("this", None) print("Deleted item's value = ", result) print("Updated Dictionary :" , wordFreqDic)
输出:
Deleted item's value = 43 Updated Dictionary : {'Hello': 56, 'test': 43}
让我们使用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")
输出:
key not found
完整的示例如下:
def main(): # Dictionary of strings and int wordFreqDic = { "Hello": 56, "at" : 23 , "test" : 43, "this" : 43 } print("Original Dictionary :" , wordFreqDic) ''' 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") ''' Deleting an entry from dictionary using pop() ''' # As 'this' key is present in dict, so pop() will delete its entry and return its value result = wordFreqDic.pop("this", None) print("Deleted item's value = ", result) print("Updated Dictionary :" , wordFreqDic) # 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) # 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") if __name__ == '__main__': main()
输出:
Original Dictionary : {'this': 43, 'at': 23, 'Hello': 56, 'test': 43} Updated Dictionary : {'this': 43, 'Hello': 56, 'test': 43} Key 'testing' not found Deleted item's value = 43 Updated Dictionary : {'Hello': 56, 'test': 43} Deleted item's value = None Updated Dictionary : {'Hello': 56, 'test': 43} Key not found