Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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 ?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading