Kir*_*aev 2 python dictionary class list
我有一个字典列表,我需要将字典值作为属性访问。
我的代码:
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)
Run Code Online (Sandbox Code Playgroud)
所以,当我写类似的东西时:
comment_list = Comments()
for comment in comment_list:
print comment['id']
Run Code Online (Sandbox Code Playgroud)
有用。
但是我想使用属性comment.id而不是comment['id']。
如何实现呢?
就像@Tim Castelijns所说的,这不是字典的工作方式。
您可以通过拥有一个Comment将idand title作为成员的类来实现您寻求的行为。
class Comment
def __init__(self, id, title):
self.id = id
self.title = title
class CommentsHolder:
def __init__(self):
self.comments = [Comment(1,'bla'),
Comment(2,'bla2'),
Comment(3, 'bla3')]
def __iter__(self):
return iter(self.comments)
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作:
for comment in CommentsHolder():
print(comment.id)
Run Code Online (Sandbox Code Playgroud)
此外,您可以查看Bunch模块,这是一个点可访问的字典。但是,如果您使用的是python 3,请注意它可能无法正常工作。(至少它不适合我。)