I have created a list of dictionaries of named tuples, keyed with an event type.
[{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}]
What would be the most pythonic method to return/print results that only contain “approved=1”, or “reviewed=1” and “approved=0”?
Advertisement
Answer
Not sure what output format you want exactly, but here’s a demo for approved == 1
.
>>> from collections import namedtuple >>> DeleteRequestDetails = namedtuple('DeleteRequestDetails', 'rid user type reviewed approved completed') >>> lst = [{'EVENT_DELETE': DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)},{'EVENT_DELETE': DeleteRequestDetails(rid=98343, user='user2', type='EVENT_DELETE', reviewed=1, approved=0, completed=0)}] >>> [v for d in lst for v in d.values() if v.approved == 1] [DeleteRequestDetails(rid=53421, user='user1', type='EVENT_DELETE', reviewed=1, approved=1, completed=0), DeleteRequestDetails(rid=13423, user='user2', type='EVENT_DELETE', reviewed=1, approved=1, completed=0)]