Home > front end >  How to filter list item list in Python
How to filter list item list in Python

Time:12-09

I have this list:

[('1',{'a':'A','b':'B', 'active':True, 'c': 'C'}),('2',{'a':'A','b':'B', 'active':False, 'c': 'C'})]

How do I filter this list using list comprehension, so I get a new list that has only 'active':True,

I've tried list comprehension like so:

[item for item in list if item.active==True]

but I ended up having AttributeError

AttributeError: 'str' object has no attribute 'active'

CodePudding user response:

Considering the snippet you provided, if you run the code you'd probably get this error:

AttributeError: 'tuple' object has no attribute 'active'

The main reason for that is that each item in your list comprehension is a tuple ('1',{'a':'A','b':'B', 'active':True, 'c': 'C'}) is the first one and ('2',{'a':'A','b':'B', 'active':False, 'c': 'C'}) is the second one. If you want to access the active, you must first access the SECOND element of your tuple (the dict containing the active key) and THEN filter by it.

Here's a sample code:

new_list = [item for item in list if item[1]["active"] == True]

However, I'll advise that if you can, you should definitely use a better data-structure to represent this data. Something like:

[{'id': 1, 'a':'A','b':'B', 'active':True, 'c': 'C'}, {'id': 2, 'a':'A','b':'B', 'active':False, 'c': 'C'}]

is probably better (but could be improved as well). For this code, the list comprehension is like so:

new_list = [item for item in list if item["active"] == True]

Hope it helps!

CodePudding user response:

This should work: [item for item in l if item[1]['active']]

you get that error because you are looking for active in the first element which is '1'. Searching in item[1] searches in the tuple.

  • Related