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

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


当前回答

这里是顶级设计方法:

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}

希望这有帮助!

其他回答

    species = {'HI': {'1': (1215.671, 0.41600000000000004),
  '10': (919.351, 0.0012),
  '1025': (1025.722, 0.0791),
  '11': (918.129, 0.0009199999999999999),
  '12': (917.181, 0.000723),
  '1215': (1215.671, 0.41600000000000004),
  '13': (916.429, 0.0005769999999999999),
  '14': (915.824, 0.000468),
  '15': (915.329, 0.00038500000000000003),
 'CII': {'1036': (1036.3367, 0.11900000000000001), '1334': (1334.532, 0.129)}}

以下代码将复制dict物种并删除不在trans_HI中的项目

trans_HI=['1025','1215']
for transition in species['HI'].copy().keys():
    if transition not in trans_HI:
        species['HI'].pop(transition)
d = {1: 2, '2': 3, 5: 7}
del d[5]
print 'd = ', d

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

解决方案1:删除

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

解决方案2:不删除

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

在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})>

只需调用del d[“key”]。

然而,在生产中,检查d中是否存在“key”始终是一个好的做法。

if 'key' in d:
    del d['key']