2

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

7
  • 2
    What exactly is [<Bob>]? A list with an object? An object? A string inside a list? Commented Jan 4, 2018 at 9:12
  • 1
    Is something like dict['people'][0].name not enough? Seems like you have a dictionary from strings to lists of objects. Commented Jan 4, 2018 at 9:17
  • [<Bob>] is and object in a list created from a django model, dict['people'][0].name gives "TypeError: 'BoundField' object does not support indexing" Commented Jan 4, 2018 at 9:23
  • This does not look like python Commented Jan 4, 2018 at 9:34
  • You are getting TypeError: 'BoundField' object does not support indexing most probably because you don't have list of objects instead you have single object. Can you confirm? Commented Jan 4, 2018 at 9:43

1 Answer 1

4

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    
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.