码迷,mamicode.com
首页 > 编程语言 > 详细

Python - 字典(dict)删除元素

时间:2015-07-25 23:04:27      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:mystra   python   字典删除元素   

字典(dict)删除元素, 可以选择两种方式, dict.pop(key)和del dict[key].


代码

# -*- coding: utf-8 -*-


def remove_key(d, key):
    r = dict(d)
    del r[key]
    return r


x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
x.pop(1)
print x

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
del x[1]
print x

x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
print remove_key(x, 1)
print x

"""
输出:
{0: 0, 2: 1, 3: 4, 4: 3}
{0: 0, 2: 1, 3: 4, 4: 3}
{0: 0, 2: 1, 3: 4, 4: 3}
{0: 0, 1: 2, 2: 1, 3: 4, 4: 3}
"""

版权声明:本文为博主原创文章,未经博主允许不得转载。

Python - 字典(dict)删除元素

标签:mystra   python   字典删除元素   

原文地址:http://blog.csdn.net/caroline_wendy/article/details/47060297

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!