[英]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. 我想动态创建一个python对象并添加多个标签:label1,label2,label3等。基于每个label_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. 但是,当我在程序末尾打印项目时,它们仅具有label1属性,该属性实际上是标签列表中的LAST标签。 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. 您没有在循环中更新label_string变量。 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). 其中enumerate是获取列表并返回对(element_number,element)的函数。
Also it can be written in one line using dict comprehensions: 也可以使用dict理解将其写成一行:
item = { label_string + str(i): label['Name'] for i, label in enumerate(labels_list)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.