mercredi 20 juillet 2016

Python list of dicts access via class attributes

I have a list of dicts and I need to access dicts values as attributes.

My code:

class Comments:

    def __init__(self):
        self.comments = [{'id': 1, 'title': 'bla'},
                         {'id': 2, 'title': 'bla2'},
                         {'id': 3, 'title': 'bla3'}]

    def __iter__(self):
        return iter(self.comments)

So, when I write something like:

comment_list = Comments()
for comment in comment_list:
    print comment['id']

It works.

But I want to use attributes as comment.id instead of comment['id'].

How to realize that?

Aucun commentaire:

Enregistrer un commentaire