Reputation: 97
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)
Upvotes: 1
Views: 1108
Reputation: 336
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)}
Upvotes: 0
Reputation: 726
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)
Upvotes: 0