Python - 字典(dict)删除元素

字典(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} """
    原文作者:SpikeKing
    原文地址: https://blog.csdn.net/caroline_wendy/article/details/47060297
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞