Home > other >  Why my loop always add the same value to my dictionnary in python?
Why my loop always add the same value to my dictionnary in python?

Time:07-01

I have this function that creates a dictionary from a list. The code is truncated to only get the most important.

def fetch_value_in_table(input_table):
    # Input table is like this : 
    # [("val_number1", "c_shift", "h_shift1"), ("val_number2", "c_shift2", "h_shift2"), ("val_number3", "c_shift3", "h_shift3")]
    # Global since output_table is used outside the function
    global output_table

    # Create the two necessary dictionaries
    output_table = {}
    dict_shift = {}

    # Loop over a line that is actually a tuple like this :
    # ("val_number1", "c_shift1", "h_shift1")
    for line in input_table: 
        # OK
        val_number = line[0]

        # OK
        c_shift = line[1]
        dict_shift['c_shift'] = c_shift

        # OK
        #... truncated
        dict_shift['h_shift'] = h_shift


        output_table[val_number] = dict_shift
        #For first loop, should be :
        # {"val_number1": {"c_shift" = c_shift1, "h_shift" = "h_shift1" }}

        # Second loop : 
        # {"val_number1": {"c_shift" = c_shift1, "h_shift" = "h_shift1" }, "val_number2": {"c_shift" = c_shift2, "h_shift" = "h_shift2" }}
        # ...

    return output_table

The expected result of output_table is:

{"val_number1": {"c_shift" = c_shift1, "h_shift" = "h_shift1" }, 
"val_number2": {"c_shift" = c_shift2, "h_shift" = "h_shift2" }, 
{"c_shift" = c_shift3, "h_shift" = "h_shift3"}}

But actually all the values are the last ones:

{"val_number1": {"c_shift" = c_shift3, "h_shift" = "h_shift3" }, 
"val_number2": {"c_shift" = c_shift3, "h_shift" = "h_shift3" }, 
{"c_shift" = c_shift3, "h_shift" = "h_shift3" }}

What do I miss to get the expected result ?

CodePudding user response:

The dict_shift actually points to the same dictionary the whole time. You need to inicialize it (dict_shift = {}) inside the loop during each iteration.

def fetch_value_in_table(input_table):
global output_table

output_table = {}

for line in input_table: 

    val_number = line[0]
    dict_shift = {}

    c_shift = line[1]
    dict_shift['c_shift'] = c_shift
    dict_shift['h_shift'] = h_shift
    output_table[val_number] = dict_shift

return output_table
  • Related