{
'tbl':'test',
'col':[
{
'id':1,
'name':"a"
},
{
'id':2,
'name':"b"
},
{
'id':3,
'name':"c"
}
]
}我有一个像上面这样的字典,我想从其中的列表中删除带有id=2的元素。我花了半天时间思考为什么modify2不使用del操作。尝试过pop,它似乎正在工作,但我不完全理解为什么del不能工作。
是否有一种使用del或pop删除的方法是解决此用例的理想方法?
import copy
test_dict = {'tbl': 'test', 'col':[{'id':1, 'name': "a"}, {'id':2, 'name': "b"}, {'id':3, 'name': "c"}]}
def modify1(dict):
new_dict = copy.deepcopy(dict)
# new_dict = dict.copy()
for i in range(len(dict['col'])):
if dict['col'][i]['id'] == 2:
new_dict['col'].pop(i)
return new_dict
def modify2(dict):
new_dict = copy.deepcopy(dict)
# new_dict = dict.copy()
for i in new_dict['col']:
if i['id']==2:
del i
return new_dict
print("Output 1 : " + str(modify1(test_dict)))
print("Output 2 : " + str(modify2(test_dict)))输出:
Output 1 : {'tbl': 'test', 'col': [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'c'}]}
Output 2 : {'tbl': 'test', 'col': [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]}我试着在类似的问题上寻找答案,但没有找到能消除我困惑的答案。
发布于 2019-06-04 13:08:55
del i只是告诉解释器i (碰巧引用字典的任意局部变量/名称)不应该再引用该字典了。它不会改变那本字典的内容。
这可以在http://www.pythontutor.com/visualize.html上可视化
在del i之前。注i引用了第二个字典(由蓝线指出):

在del i之后。注意局部变量i是如何从本地命名空间(蓝色框)中删除的,但是它引用的字典仍然存在。

与del i (将引用修改为字典)相反,dict.pop(key)修改字典。
发布于 2019-06-04 13:06:39
在Python 3中,您可以这样做:
test_dict = {**test_dict, 'col': [x for x in test_dict['col'] if x['id'] != 2]}发布于 2019-06-04 13:04:18
这是一种使用理解的方法。
Ex:
data = {'tbl': 'test', 'col': [{'id': 1, 'name': 'a'}, {'id': 2, 'name': 'b'}, {'id': 3, 'name': 'c'}]}
data['col'] = [i for i in data['col'] if i["id"] != 2]
print(data)输出:
{'col': [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'c'}], 'tbl': 'test'}https://stackoverflow.com/questions/56444477
复制相似问题