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

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


当前回答

使用del可以删除传递该值键的dict值

链接:德尔法

del dictionary['key_to_del']

其他回答

这里是顶级设计方法:

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}

希望这有帮助!

在Python 3中,“dict”对象没有属性“remove”。

但使用immutables包,可以执行允许对Map对象应用更改并创建新的(派生的)Maps的突变:

import immutables
map = immutables.Map(a=1, b=2)
map1 = map.delete('b')
print(map, map1)
# will print:
#   <immutables.Map({'b': 2, 'a': 1})>
#   <immutables.Map({'a': 1})>

可以试试我的方法。在一行。

yourList = [{'key':'key1','version':'1'},{'key':'key2','version':'2'},{'key':'key3','version':'3'}]
resultList = [{'key':dic['key']} for dic in yourList if 'key' in dic]
print(resultList)

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

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)

使用del可以删除传递该值键的dict值

链接:德尔法

del dictionary['key_to_del']