Search code examples
pythonlistdictionarydeep-copy

Deleting an element from a list inside a dict in Python


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

I have a dictionary like the one above and I want to remove the element with id=2 from the list inside it. I wasted half a day wondering why modify2 is not working with del operation. Tried pop and it seems to be working but I don't completely understand why del doesn't work.

Is there a way to delete using del or pop is the ideal way to address this use case?

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:

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'}]}

I tried looking for answers on similar questions but didn't find the one that clears my confusion.


Solution

  • del i just tells the interpreter that i (an arbitrary local variable/name that happens to reference to a dictionary) should not reference that dictionary any more. It does not change the content of that dictionary whatsoever.

    This can be visualized on http://www.pythontutor.com/visualize.html:

    Before del i. Note i references the second dictionary (noted by the blue line):

    enter image description here

    After del i. Note how the local variable i is removed from the local namespace (the blue box) but the dictionary it referenced to still exists.

    enter image description here

    Contrary to del i (which modifies the reference to the dictionary), dict.pop(key) modifies the dictionary.