Home > Back-end >  Why the value of the first appended dictionary is changed when a second one is appended?
Why the value of the first appended dictionary is changed when a second one is appended?

Time:12-24

In the isolated code snippet below I'm trying to get this result: lista_skafwn_to_insert: [{'SERVICE REPORTS': ['1']}, {'SERVICE REPORTS': ['2']}],

but instead I get this: lista_skafwn_to_insert: [{'SERVICE REPORTS': ['2']}, {'SERVICE REPORTS': ['2']}].

Why the value of the first dictionary is changed and equals to the value of the last dictionary?

The moment sr_ged is 1 I append it to a list. Then the sxima_skafous dictionary uses this list as a value in "SERVICE REPORTS" key.

Then I append this dictionary to the lista_skafwn_to_insert list.

So the first element of the lista_skafwn_to_insert is this {'SERVICE REPORTS': ['1']}.

Then I clear lista_service_reports and I assign a new value on sr_ged and I repeat the above proccess.

Why the value of the first dictionary is affected when it's been appended BEFORE any change occurs in sr_ged and lista_sesrvice_reports?

Code snippet:

lista_skafwn_to_insert = []
lista_service_reports = []

sr_ged = input("sr_ged: ")

lista_service_reports.append(sr_ged)

sxima_skafous = {"SERVICE REPORTS": lista_service_reports}

lista_skafwn_to_insert.append(sxima_skafous)

print('lista_skafwn_to_insert:'   str(lista_skafwn_to_insert))

lista_service_reports.clear()

sr_ged = input("sr_ged: ")

lista_service_reports.append(sr_ged)

sxima_skafous = {"SERVICE REPORTS": lista_service_reports}

lista_skafwn_to_insert.append(sxima_skafous)

print('lista_skafwn_to_insert: '   str(lista_skafwn_to_insert))

CodePudding user response:

Both dictionaries have a reference to the same list. The clear method only mutates the original list. It doesn't create a new one. Change the clear call to this:

lista_service_reports = []

This will start a whole new list to store in the second dictionary.

CodePudding user response:

Try using .copy() like this. A list is a pointer, so... that's the point!

    lista_skafwn_to_insert = []
    lista_service_reports = []
    
    sr_ged = input("sr_ged: ")
    
    lista_service_reports.append(sr_ged)
    
    sxima_skafous = {"SERVICE REPORTS": lista_service_reports.copy()}
    
    lista_skafwn_to_insert.append(sxima_skafous)
    
    print('lista_skafwn_to_insert:'   str(lista_skafwn_to_insert))
    
    lista_service_reports.clear()
    
    sr_ged = input("sr_ged: ")
    
    lista_service_reports.append(sr_ged)
    
    sxima_skafous = {"SERVICE REPORTS": lista_service_reports.copy()}
    
    lista_skafwn_to_insert.append(sxima_skafous)
    
    print('lista_skafwn_to_insert: '   str(lista_skafwn_to_insert))
  • Related