1

The code that I have written:

def function_1(object_1, list_1):
list_to_return = []
for x in list_1:
    object_1['key_1'] = [x]
    list_to_return.append(object_1)
return list_to_return

if __name__ == "__main__":
    object_main = {
        "key_1":['item1'],
        "key_2":['item1', 'item2']
    }
    list1_main = ['1','2', '3']
    ret_val = function_1(object_main, list1_main)
    print(ret_val)

The code is written to replace items of key_1 in the object with each of the items in list: list1_main. The function replaces the key as expected within the function. But the output from the print statement is as follows:

[{'key_1': ['3'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}]

The expected output is:

[{'key_1': ['1'], 'key_2': ['item1', 'item2']}, {'key_1': ['2'], 'key_2': ['item1', 'item2']}, {'key_1': ['3'], 'key_2': ['item1', 'item2']}]

Not sure why the code does this. Python Version: 3.8

SummmerFort
  • 369
  • 3
  • 8

2 Answers2

1

you are passing by reference, The key is to use .copy on the dict. Note that the list returned in this solution below will NOT contain any reference to the original dict, but the original dict will be affected. if you want to preserve the original dict, then I suggest you generate a deep copy as well.


def function_1(object_1:Dict, list_1):
    list_to_return = []
    for x in list_1:
        object_1['key_1'] = [x] # here u may want to manipulate a copy of ur dict instead
        list_to_return.append(object_1.copy()) # here we copy the dict

    return list_to_return

if __name__ == "__main__":
    object_main = {
        "key_1":['item1'],
        "key_2":['item1', 'item2']
    }
    list1_main = ['1','2', '3']
    ret_val = function_1(object_main, list1_main)
    print(ret_val)
Cryptoharf84
  • 371
  • 1
  • 12
0

You are appending same dictionary to list_to_return every time. Because dictionaries are mutable. You should copy it every time. Also you are changing given dict, you should copy it too:

def function_1(object_1, list_1):
    object_1 = object_1.copy()
    list_to_return = []
    for x in list_1:
        object_1['key_1'] = [x]
        list_to_return.append(object_1.copy())
    return list_to_return


if __name__ == "__main__":
    object_main = {
        "key_1":['item1'],
        "key_2":['item1', 'item2']
    }

    list1_main = ['1','2', '3']
    ret_val = function_1(object_main, list1_main)
    print(ret_val)

Ekrem Dinçel
  • 1,053
  • 6
  • 17