首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从Python的dict中的列表中删除元素

从Python的dict中的列表中删除元素
EN

Stack Overflow用户
提问于 2019-06-04 13:01:46
回答 5查看 263关注 0票数 4
代码语言:javascript
运行
复制
{  
   'tbl':'test',
   'col':[  
      {  
         'id':1,
         'name':"a"
      },
      {  
         'id':2,
         'name':"b"
      },
      {  
         'id':3,
         'name':"c"
      }
   ]
}

我有一个像上面这样的字典,我想从其中的列表中删除带有id=2的元素。我花了半天时间思考为什么modify2不使用del操作。尝试过pop,它似乎正在工作,但我不完全理解为什么del不能工作。

是否有一种使用del或pop删除的方法是解决此用例的理想方法?

代码语言:javascript
运行
复制
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)))

输出:

代码语言:javascript
运行
复制
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'}]}

我试着在类似的问题上寻找答案,但没有找到能消除我困惑的答案。

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 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)修改字典

票数 2
EN

Stack Overflow用户

发布于 2019-06-04 13:06:39

在Python 3中,您可以这样做:

代码语言:javascript
运行
复制
test_dict = {**test_dict, 'col': [x for x in test_dict['col'] if x['id'] != 2]}
票数 3
EN

Stack Overflow用户

发布于 2019-06-04 13:04:18

这是一种使用理解的方法。

Ex:

代码语言:javascript
运行
复制
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)

输出:

代码语言:javascript
运行
复制
{'col': [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'c'}], 'tbl': 'test'}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56444477

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档