python字典怎么删除键

发布时间:2022-07-13 09:51:21 人气:244 作者:多测师

  Python中的字典是另一种可变容器模型,且可存储任意类型对象。键一般是唯一的,如果重复最后的一个键值对会替换前面的,值不需要唯一。

  Python删除字典元素的4种方法

  1. Python字典的clear()方法(删除字典内所有元素)

  #!/usr/bin/python

  # -*- coding: UTF-8 -*-

  dict = {'name': '我的博客地址', 'alexa': 10000, 'url': }

  dict.clear(); # 清空词典所有条目

  2. Python字典的pop()方法(删除字典给定键 key 所对应的值,返回值为被删除的值)

  #!/usr/bin/python

  # -*- coding: UTF-8 -*-

  site= {'name': '我的博客地址', 'alexa': 10000, 'url':}

python字典怎么删除键

  pop_obj=site.pop('name') # 删除要删除的键值对,如{'name':'我的博客地址'}这个键值对

  print pop_obj # 输出 :我的博客地址

  3. Python字典的popitem()方法(随机返回并删除字典中的一对键和值)

  #!/usr/bin/python

  # -*- coding: UTF-8 -*-

  site= {'name': '我的博客地址', 'alexa': 10000, 'url':'}

  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':}

  del site['name'] # 删除键是'name'的条目

  del site # 清空字典所有条目

  以上内容为大家介绍了python字典怎么删除键,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注多测师。https://www.e70w.com/xwzx/


返回列表
在线客服
联系方式

热线电话

17727591462

上班时间

周一到周五

二维码
线