为什么我的循环总是将相同的值添加到python的字典中?



我有一个从列表创建字典的函数。代码被截断,只留下最重要的部分。

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

output_table的预期结果为:

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

但实际上所有的值都是最后一个:

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

为了得到预期的结果,我错过了什么?

dict_shift实际上一直指向同一个字典。您需要在每次迭代期间在循环中初始化它(dict_shift = {})。

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

相关内容

  • 没有找到相关文章

最新更新