简体   繁体   English

Python在For循环中添加字典属性仅会在列表中添加最后一项

[英]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.

相关问题 dict1[d] = c 仅将 list2 中的最后一项添加为字典中的值,我该如何解决? - dict1[d] = c adds only last item in list2 as a value in dictionary, how can I solve it? Python字典理解只接受列表中的最后一项值 - Python dictionary comprehension takes only last item in list for value Python/Pandas for 循环遍历列表,只处理列表中的最后一项 - Python/Pandas for loop through a list only working on the last item in the list 字典仅在 for 循环中添加最后一个键值对 - Dictionary only adds in the last key value pair in for loop while循环中仅将最后一项追加到列表中(Python) - Only the last item is being appended to a list in a while loop (Python) 嵌套的 Python for 循环仅适用于列表中的最后一项 - Nested Python for loop only works with the last item in a list openpyxl 在循环中添加图像,仅添加所有图像的最后一个图像 - openpyxl adding image in loop, adds only last images for al the images 字典仅返回列表值中的最后一项 - Dictionary returning only the Last Item in List Value Python for循环仅返回字典的最后一个值 - Python for loop only returning last value of a dictionary 嵌套的for循环仅对列表的最后一项执行 - Nested for loop only executing for last item of list
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM