如何在Python中从字典中删除项目?

在不修改原始词典的情况下,如何获取删除了该项的另一个词典?


当前回答

解决方案1:删除

info = {'country': 'Iran'}
country = info.pop('country') if 'country' in info else None

解决方案2:不删除

info = {'country': 'Iran'}
country = info.get('country') or None

其他回答

pop改变了字典。

 >>> lol = {"hello": "gdbye"}
 >>> lol.pop("hello")
     'gdbye'
 >>> lol
     {}

如果你想保留原件,你可以复制它。

d = {1: 2, '2': 3, 5: 7}
del d[5]
print 'd = ', d

结果:d={1:2,“2”:3}

我认为你的解决方案是最好的方法。但如果你想要另一个解决方案,你可以使用旧字典中的关键字创建一个新字典,而不包括你指定的关键字,如下所示:

>>> a
{0: 'zero', 1: 'one', 2: 'two', 3: 'three'}
>>> {i:a[i] for i in a if i!=0}
{1: 'one', 2: 'two', 3: 'three'}

下面是使用列表理解的另一种变体:

original_d = {'a': None, 'b': 'Some'}
d = dict((k,v) for k, v in original_d.iteritems() if v)
# result should be {'b': 'Some'}

该方法基于本文中的答案:从字典中删除带有空字符串的键的有效方法

对于Python 3,这是

original_d = {'a': None, 'b': 'Some'}
d = dict((k,v) for k, v in original_d.items() if v)
print(d)

这里是顶级设计方法:

def eraseElement(d,k):
    if isinstance(d, dict):
        if k in d:
            d.pop(k)
            print(d)
        else:
            print("Cannot find matching key")
    else:
        print("Not able to delete")


exp = {'A':34, 'B':55, 'C':87}
eraseElement(exp, 'C')

我将字典和我想要的键传递到我的函数中,验证它是否是字典,以及键是否正常,如果两者都存在,则从字典中删除值并打印出剩余的值。

输出:{“B”:55,“A”:34}

希望这有帮助!