Python 如何迭代列表对象以在字典中插入值
我有列表对象查询集,比如Python 如何迭代列表对象以在字典中插入值,python,dictionary,Python,Dictionary,我有列表对象查询集,比如 **class_details** [<obj1>, <obj2>, <obj3>] 您每次都在迭代class\u详细信息并替换class\u信息。请注意,如果在循环中执行print(),将获得每个类的输出 在你的帖子中,你说你想要一个值字典,它是所有值的数组;如果是这样,第一步,在循环外初始化一个资源,然后在循环内更新它。在本例中,代码的工作方式如下 #init class_info outside of the loop cl
**class_details**
[<obj1>, <obj2>, <obj3>]
您每次都在迭代
class\u详细信息
并替换class\u信息
。请注意,如果在循环中执行print(),将获得每个类的输出
在你的帖子中,你说你想要一个值字典,它是所有值的数组;如果是这样,第一步,在循环外初始化一个资源,然后在循环内更新它。在本例中,代码的工作方式如下
#init class_info outside of the loop
class_info = {
'Sub Type': [],
'Sch Name': [],
'High Amount': [],
'Roll Number': [],
}
for i in class_details:
class_info['Sub Type'].append(i.sub_type)
class_info['Sch Name'].append(i.name)
class_info['High Amount'].append(i.highestscore)
class_info['Roll Number'].append(i.subnumber)
return class_info
#init class_info outside of the loop
class_info = {
'Sub Type': [],
'Sch Name': [],
'High Amount': [],
'Roll Number': [],
}
for i in class_details:
class_info['Sub Type'].append(i.sub_type)
class_info['Sch Name'].append(i.name)
class_info['High Amount'].append(i.highestscore)
class_info['Roll Number'].append(i.subnumber)
return class_info