Search code examples
pythonlistdictionarygeneratornested-loops

Is there a way to access each element's attribute in generator in nested for loop?


I want to run a nested loop over a generator and a list. Within the loop, I want to access each element's attribute.

I found similar code questions about looping over an object's attributes, but I wasn't able to solve the problem I'm having.

Below is my code work:

gen = api.search_submissions() # gen is generator of submissions

f_list = ['id','title']

sub_dict = {
    'id':[],
    'title':[]
}

for sub in gen:
    for name in f_list:
        sub_dict[name].append(sub.name)

I ran into a problem that python does not assign values to 'name' inside .append method.

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
AttributeError: 'submission' object has no attribute 'name'

How can I get around with this problem? Thank you.


Solution

  • I ran into a problem that python does not loop over 'name' inside .append method.

    The loop is looping over the values of f_list and assigning them to the variable name. The problem is that attribute access expressions, such as sub.name, do not check the local scope for a matching variable and replace the name with its value. The presence or absence of a local variable named name does not change the fact that sub.name will look for an attribute literally named "name" on the sub object.

    You can use getattr to get an attribute of an object, given a string holding the attribute name.

    sub_dict[name].append(getattr(sub,name))