简体   繁体   中英

Python Adding Dictionary Attributes in For Loop Only Adds Last Item in List

I want to dynamically create a python object and add multiple labels: label1, label2, label3, etc. Based on the items that are present in each labels_list. However, when I print my items at the end of the program they only have a label1 attribute which is actually the LAST label in the list of labels. Why is this? And how can I go about dynamically adding all of these labels as attributes to my dictionary?

item = {}
item['filename'] = file_name

count = 1
label_string = 'label'
label_string += str(count)

for label in labels_list:
    item[label_string] = label['Name']
    count+=1

print(item)    

Below should work I guess,

item = {}
item['filename'] = file_name

count = 1
label_string_base = 'label'
label_string = label_string_base + str(count)

for label in labels_list:
    item[label_string] = label['Name']
    count+=1
    label_string = label_string_base + str(count)


print(item)   

You are not updating label_string variable in loop. So you write in one dictionary key. One of the right methods is:

item = {}
item['filename'] = file_name

count = 1
label_string = 'label'

for i, label in enumerate(labels_list):
    item[label_string + str(i)] = label['Name']

print(item)    

Where enumerate is function that gets a list and returns pairs (element_number, element).
Also it can be written in one line using dict comprehensions:

 item = { label_string + str(i): label['Name'] for i, label in enumerate(labels_list)}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM