首页 > 解决方案 > 从 Python 中的 dict 内的列表中删除元素

问题描述

{  
   'tbl':'test',
   'col':[  
      {  
         'id':1,
         'name':"a"
      },
      {  
         'id':2,
         'name':"b"
      },
      {  
         'id':3,
         'name':"c"
      }
   ]
}

我有一本像上面这样的字典,我想id=2从里面的列表中删除元素。我浪费了半天时间想知道为什么modify2不使用del操作。试过了pop,它似乎工作,但我不完全明白为什么del不工作。

有没有办法删除 usingdel或 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'}]}

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

标签: pythonlistdictionarydeep-copy

解决方案


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

test_dict = {**test_dict, 'col': [x for x in test_dict['col'] if x['id'] != 2]}

推荐阅读