ITPub博客

首页 > IT职业 > IT生活 > python怎样删除字典中的元素

python怎样删除字典中的元素

IT生活 作者:fengwei 时间:2021-09-11 10:17:04 0 删除 编辑

python删除字典中元素的方法:

1、使用clear()方法删除字典内所有元素

clear()方法语法:dict.clear()

示例:

dict = {'Name': 'Zara', 'Age': 7};

print "Start Len : %d" %  len(dict)
dict.clear()
print "End Len : %d" %  len(dict)

输出结果如下:

Start Len : 2

End Len : 0

2、使用pop()方法删除字典给定键key及对应的值

pop()方法语法:pop(key[,default])

>>> x = {'a':1,'b':2}
>>> x.pop('a')
1
>>> x
{'b': 2}

3、使用popitem() 方法返回并删除字典中的最后一对键和值。

popitem()方法语法:popitem()

>>> x
{'url': 'www.iplaypython.com', 'title': 'python web site'}
>>> x.popitem()
('url', 'www.iplaypython.com')
>>> x
{'title': 'python web site'}

更多Python知识请关注Python视频教程栏目。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/2799/viewspace-2833698/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-08-16

  • 博文量
    90
  • 访问量
    676