Python 刪除字典元素的4種方法
- 2020 年 1 月 6 日
- 筆記
1. Python字典的clear()方法(刪除字典內所有元素)
#!/usr/bin/python # -*- coding: UTF-8 -*- dict = {'name': '我的部落格地址', 'alexa': 10000, 'url': 'http://blog.csdn.net/uuihoo/'} dict.clear(); # 清空詞典所有條目
2. Python字典的pop()方法(刪除字典給定鍵 key 所對應的值,返回值為被刪除的值)
#!/usr/bin/python # -*- coding: UTF-8 -*- site= {'name': '我的部落格地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'} pop_obj=site.pop('name') # 刪除要刪除的鍵值對,如{'name':'我的部落格地址'}這個鍵值對 print pop_obj # 輸出 :我的部落格地址
3. Python字典的popitem()方法(隨機返回並刪除字典中的一對鍵和值)
#!/usr/bin/python # -*- coding: UTF-8 -*- site= {'name': '我的部落格地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'} pop_obj=site.popitem() # 隨機返回並刪除一個鍵值對 print pop_obj # 輸出結果可能是{'url','http://blog.csdn.net/uuihoo/'}
4. del 全局方法(能刪單一的元素也能清空字典,清空只需一項操作)
#!/usr/bin/python # -*- coding: UTF-8 -*- site= {'name': '我的部落格地址', 'alexa': 10000, 'url':'http://blog.csdn.net/uuihoo/'} del site['name'] # 刪除鍵是'name'的條目 del site # 清空字典所有條目