Search code examples
pythondictionarydel

python "del" statment deletes multiple dicts


i have a problem with the del statement for dicts since i get multiple deletes. So for example my code looks like this:

info_dict = {'parent1':{'exon':{'exon1':{'str_0':1, 'end_0':1}, 'exon2':{'str_0':2, 'end_0':2}}},'parent2':{'exon':{'exon1':{'str_0':1, 'end_0':1}, 'exon3':{'str_0':3, 'end_0':3}}}}
print info_dict 
#now i want to delete this key: 
del info_dict.get('parent1').get('exon').get('exon1')['end_0']
#as an result i get this: 
print info_dict 
{'parent1':{'exon':{'exon1':{'str_0':1}, 'exon2':{'str_0':2, 'end_0':2}}},'parent2':{'exon':{'exon1':{'str_0':1}, 'exon3':{'str_0':3, 'end_0':3}}}}

As you can see the del statement deletes the right key from 'parent1'. But it also deletes the same key from dict 'parent2'.

In my code i loop through the dicts with:

for parent_key in info_dict: 
    "check something and del"

If i run the code like above the del statement deletes just one key. But when i loop it, it del multiple keys. I checked my code several times an it is all right. At this point i have no clue what is wrong... Sorry i do not show you the whole code, it seems to big. But maybe someone has an idea what the problem is. Thank you


Solution

  • Somewhere in your actual code you are creating references to dicts so when you change in one place you change all the references.

    d = {1:{2:3}}
    
    d1 = d # creates a reference so d1 id d
    print(d)
    print(d1)
    del d[1]
    
    print(d)
    print(d1)
    

    Output:

    {1: {2: 3}}
    {1: {2: 3}}
    {} # both empty as both are the same dict/object
    {}
    

    Now making an actual copy with copy.deepcopy:

    from copy import deepcopy
    
    d = {1:{2:3}}
    
    d1 = deepcopy(d) # creates a copy/new object
    print(d)
    print(d1)
    del d[1]
    
    print(d)
    print(d1)
    

    Output:

    {1: {2: 3}}
    {1: {2: 3}}
    {} # only d is empty as we created a new object for d1
    {1: {2: 3}}