如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
如何在Python中从字典中删除项目?
在不修改原始词典的情况下,如何获取删除了该项的另一个词典?
当前回答
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)
其他回答
pop改变了字典。
>>> lol = {"hello": "gdbye"}
>>> lol.pop("hello")
'gdbye'
>>> lol
{}
如果你想保留原件,你可以复制它。
del陈述就是你要找的。如果您有一个名为foo的字典,其键名为“bar”,则可以像这样从foo中删除“bar”:
del foo['bar']
请注意,这将永久修改正在操作的词典。如果您想保留原始词典,则必须事先创建一个副本:
>>> foo = {'bar': 'baz'}
>>> fu = dict(foo)
>>> del foo['bar']
>>> print foo
{}
>>> print fu
{'bar': 'baz'}
dict调用生成一个浅显的副本。如果需要深度复制,请使用copy.depcopy。
为了方便,您可以复制并粘贴以下方法:
def minus_key(key, dictionary):
shallow_copy = dict(dictionary)
del shallow_copy[key]
return shallow_copy
没有,除了
def dictMinus(dct, val):
copy = dct.copy()
del copy[val]
return copy
然而,通常只创建稍微修改过的字典的副本可能不是一个好主意,因为这会导致相对较大的内存需求。通常最好记录旧字典(如果需要),然后修改它。
这里是顶级设计方法:
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}
希望这有帮助!
>>> def delete_key(dict, key):
... del dict[key]
... return dict
...
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>
这不做任何错误处理,它假设密钥在dict中,您可能需要先检查它,如果没有,则引发