• 技术文章 >常见问题 >Python常见问题

    python怎样删除字典中的元素

    yangyang2020-05-13 09:43:33原创5831

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

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

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

    示例:

    1

    2

    3

    4

    5

    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])

    1

    2

    3

    4

    5

    >>> x = {'a':1,'b':2}

    >>> x.pop('a')

    1

    >>> x

    {'b': 2}

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

    popitem()方法语法:popitem()

    1

    2

    3

    4

    5

    6

    >>> x

    {'url': 'www.iplaypython.com', 'title': 'python web site'}

    >>> x.popitem()

    ('url', 'www.iplaypython.com')

    >>> x

    {'title': 'python web site'}

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

    专题推荐:python
    上一篇:python找出几个数最大值的方法 下一篇:python怎么让代码无效

    相关文章推荐

    • python中lambda的用法• python中画图出现中文乱码怎么解决• python读取文本内容中文乱码怎么解决

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网