从Python 字典中删除键值

时间:2020-02-23 14:43:45  来源:igfitidea点击:

在本教程中,我们将看到如何从Python中的字典中删除键。
有多种方法可以做到这一点.Llet探索从字典中删除密钥的不同方式。

使用POP方法

我们可以使用pop方法从字典中删除键。
这是从字典中删除密钥的最佳方法。

countryDict={"Netherlands":"Amsterdam","China":"Beijing","Australia":"Canberra","UK":"London"}
print("countryDict before pop:",countryDict)
removedCapital=countryDict.pop("China")
print("countryDict after pop:",countryDict)
print("Removed capital:",removedCapital)
#If you try to remove key which is not present in the key, then it will raise KeyError
removedCountry=countryDict.pop("USA")

输出:

countryDict before pop: {'Netherlands': 'Amsterdam', 'China': 'Beijing', 'Australia': 'Canberra', 'UK': 'London'}
countryDict after pop: {'Netherlands': 'Amsterdam', 'Australia': 'Canberra', 'UK': 'London'}
Removed capital: Beijing
—————————————————————————
KeyError                                  Traceback (most recent call last)
 in ()
      6
      7 #If you try to remove key which is not present in the key, then it will raise KeyError
—-> 8 removedCountry=countryDict.pop(“USA")
      9 
KeyError: 'USA'

正如我们可以看到的,当我们成功地从字典中删除关键"China"时,但是当我们尝试删除在字典中不存在的键时,我们就会获得KeyError。
如果将默认值传递给Pop方法,那么我们赢了g get keyerror。

countryDict={"Netherlands":"Amsterdam","China":"Beijing","Australia":"Canberra","UK":"London"}
print("countryDict before pop:",countryDict)
removedCapital=countryDict.pop("USA","Dummy")
print("countryDict after pop:",countryDict)

输出:

countryDict before pop: {'Netherlands': 'Amsterdam', 'China': 'Beijing', 'Australia': 'Canberra', 'UK': 'London'}
countryDict after pop: {'Netherlands': 'Amsterdam', 'China': 'Beijing', 'Australia': 'Canberra', 'UK': 'London'}

正如我们所看到的,当我们向POP方法提供默认值时,我们没有得到KeyError并且Dict没有改变。

使用del运算符

我们还可以使用Del运算符从字典中删除密钥。
让我们通过示例来理解。

countryDict={"Netherlands":"Amsterdam","China":"Beijing","Australia":"Canberra","UK":"London"}
print("countryDict before removing key china:",countryDict)
if 'China' in countryDict:
    del countryDict['China']
print("countryDict after removing key china:",countryDict)

输出:

countryDict before removing key china: {'Netherlands': 'Amsterdam', 'China': 'Beijing', 'Australia': 'Canberra', 'UK': 'London'}
countryDict adter removing key china: {'Netherlands': 'Amsterdam', 'Australia': 'Canberra', 'UK': 'London'}