将字典列表转换为 python 中的对象列表
Converting list of dictionaries to list of objects in python
假设我有以下人员词典列表 -
[
{
'Name' : 'Michael',
'Age' : '19',
'Role' : 'Manager'
},
{
'Name' : 'Josh',
'Age' : '20',
'Role' : 'Student'
}
]
等等...
我从 API 中获取此数据,并希望将每个字典都作为 class 人的对象。
我很难在 python 中编码,甚至不知道从哪里开始?我应该用 for 循环迭代列表,然后一个一个地构造每个变量吗?
提前致谢!
Person
的例子class:
class Person:
def __init__(self, name, age, role):
self.name = name
self.age = age
self.role = role
# other methods
遍历数据列表并将其转换为Person
对象
new_lst = []
for i in lst: # lst is the list that contains the data
person = Person(i["Name"], i["Age"], i["Role"])
new_lst.append(person)
假设我有以下人员词典列表 -
[
{
'Name' : 'Michael',
'Age' : '19',
'Role' : 'Manager'
},
{
'Name' : 'Josh',
'Age' : '20',
'Role' : 'Student'
}
]
等等... 我从 API 中获取此数据,并希望将每个字典都作为 class 人的对象。 我很难在 python 中编码,甚至不知道从哪里开始?我应该用 for 循环迭代列表,然后一个一个地构造每个变量吗?
提前致谢!
Person
的例子class:
class Person:
def __init__(self, name, age, role):
self.name = name
self.age = age
self.role = role
# other methods
遍历数据列表并将其转换为Person
对象
new_lst = []
for i in lst: # lst is the list that contains the data
person = Person(i["Name"], i["Age"], i["Role"])
new_lst.append(person)