akashk akashk - 3 months ago 8
Python Question

Why object is taking last value in list?

Why object is taking last value in list

ddd = [1,2]
master_list = []
for ridx in range(1):
row_list = [] ; row_data = {} ; header_dic = {} ;
header_dic['background-color'] = 'green'
row_list.append(header_dic)
for metric_id in range(2):
row_data['background-color'] = ddd[metric_id]
row_list.append(row_data)
master_list.append(row_list)

print(master_list)


Output coming :

[[{'background-color': 'green'}, {'background-color': 2}, {'background-color': 2}]]


Expected output :

[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]

Answer

Just move row_data in inner loop.

ddd = [1,2]
master_list = []
for ridx in range(1):
    row_list = [] ; header_dic = {} ; 
    header_dic['background-color'] = 'green'
    row_list.append(header_dic)

    for metric_id in range(2):
        row_data = {} 
        row_data['background-color'] = ddd[metric_id]
        row_list.append(row_data)
    master_list.append(row_list)

print(master_list)  

And you will get the expected output:

[[{'background-color': 'green'}, {'background-color': 1}, {'background-color': 2}]]
Comments