[Python] Replace values in a list of dictionaries using for loop [duplicate]

Discussão em 'Python' iniciado por Stack, Fevereiro 5, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following simple program.

    params = {'a':1, 'b':2, 'c':3}

    params_array = [params]*10

    for i in range(len(params_array)):
    params_array['a'] = i
    print(params_array)

    print(params_array)



    The params_array initially looks like this:

    [{'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}, {'a': 1, 'b': 2, 'c': 3}]


    Each element of the array gets updated correctly within each iteration of the for loop:

    {'a': 0, 'b': 2, 'c': 3}
    {'a': 1, 'b': 2, 'c': 3}
    {'a': 2, 'b': 2, 'c': 3}
    {'a': 3, 'b': 2, 'c': 3}
    {'a': 4, 'b': 2, 'c': 3}
    {'a': 5, 'b': 2, 'c': 3}
    {'a': 6, 'b': 2, 'c': 3}
    {'a': 7, 'b': 2, 'c': 3}
    {'a': 8, 'b': 2, 'c': 3}
    {'a': 9, 'b': 2, 'c': 3}


    But the params_array that comes out of the for loop has all the values replaced with the last value.

    [{'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}, {'a': 9, 'b': 2, 'c': 3}]


    What am I doing wrong? Is it a variable scope issue? I thought this method is pretty standard, but I'm not getting the result I expected.

    Continue reading...

Compartilhe esta Página