1

I have an object

class Lists:
    pass

for item in items_list:
    name = str(item.theme)
    if hasattr(Lists, name):
        setattr(Lists, name, [])
        append(value) to this array

    else:
        setattr(Lists, name, [])

If this object has this attribute I only to append the value to this list. Otherwise I want to add this attribute to the object and then append the value to this list.

2
  • post the items_list contents and elaborate the expected contents of this array Commented Nov 10, 2017 at 13:28
  • getattr(Lists, name).append(value)? Commented Nov 10, 2017 at 13:28

2 Answers 2

2

You could use setattr + getattr. Here's a small example.

class A:
    pass
attr = ['foo', 'bar', 'baz', 'foo', 'foo', 'baz']
vals = range(len(attr))

for i, j in zip(attr, vals):
     if not hasattr(A, i):
         setattr(A, i, [])  # the attribute is created if it didn't already exist

     getattr(A, i).append(j)
vars(A)     
mappingproxy({..., 'bar': [1], 'baz': [2, 5], 'foo': [0, 3, 4]})
Sign up to request clarification or add additional context in comments.

4 Comments

How I can print array or object on html page? like console for js
@Aaron that seems like a completely different and unrelated question. You should check out How to Ask
@Aaron Sorry? Can you explain how that is related to this question? If you have another question, please open another thread.
@cᴏʟᴅsᴘᴇᴇᴅ yes, and you start push me a minus )
0

To add an attribute to the object use:

Lists.name = lambda: None

Your code will now look like :

class Lists:
    pass   

for item in items_list:
    name = str(item.theme)
    if hasattr(Lists, name):
        setattr(Lists, name, [])
        append(value) to this array

    else:
        Lists.name = lambda: None
        setattr(Lists, name, [])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.