当前位置:首页 > Python教程 > python技巧

python 删除字典某个key(键)及对应值

删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

显示删除一个字典用del命令,如下实例:

            #
            !/usr/bin/python
            
#
             -*- coding: UTF-8 -*-
             
dict = {Name: Zara, Age: 7, Class: First};
 
del dict[Name]; # 删除键是‘Name‘的条目
dict.clear();     # 清空词典所有条目del dict ;        # 删除词典print"dict[‘Age‘]: ", dict[Age];
print"dict[‘School‘]: ", dict[School];

但这会引发一个异常,因为用del后字典不再存在:

dict[Age]:
Traceback (most recent call last):
  File "test.py", line 8, in <module>
    print"dict[‘Age‘]: ", dict[Age];
TypeError: type object is unsubscriptable

希望对你有帮助~

原文:https://www.cnblogs.com/hcy-fly/p/9146256.html


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!

相关教程推荐

其他课程推荐