Python将对象的属性作为dict值访问

时间:2018-01-04 09:11:16

标签: python dictionary

假设我有一个dict

dict = {'people': [<Bob>], 'animals': [<Frank>]}

鲍勃和弗兰克是两个具有属性的对象:

Bob = MethodForCreateAPerson(){          Frank = MethodForCreateAnimals(){
    name = 'Bob',                            name = 'Frank',
    age = 30,                                age = 6,
    sex = 'm'                                sex = 'w'
}                                         }

问题是:

如果他们是dict的值,我如何访问Bob和Frank的属性?

换句话说,我需要检查从dict.values()返回的对象的属性。

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您的结构实际上看起来并不完全清楚,但如果您的字典中的值是对象列表,那么以下内容将起作用:

people = dict['people'] #  get the people list
bob = people[0] #  the first entry in that list is bob
name_of_bob = bob.name #  access the name of bob

also_name_of_bob = dict['people'][0].name #  does the same but in 1 line

访问这样的人员列表可能不是您想要在代码中执行的操作,但您可能希望迭代所有这样的人:

for person in dict['people']:
    person_name = person.name
    # do something with the person or the name