JungleFever
JungleFever

Reputation: 47

Python Accessing attributes of an object as a dict value

suppose I have a dict like that:

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

Bob and Frank are two objects with attributes:

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

The Question is:

How can I access Bob's and Frank's attributes when they are values of a dict?

In other words, I need to check the attributes of the objects returned from dict.values().

Thanks for help

Upvotes: 2

Views: 6175

Answers (1)

Glenn D.J.
Glenn D.J.

Reputation: 1965

It is not entirely clear what your structure actually looks like but if your values in your dictionary are lists of objects then the following will work:

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

Accessing the people list like this is probably not what you would like to do in your code though, you would likely want to iterate over all the people like this:

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

Upvotes: 4

Related Questions