首页 > 代码库 > Python - 字典(dict)删除元素

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}
"""

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

Python - 字典(dict)删除元素