Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter a dictionary if value of a key is true

I am totally new to Python (day 1). I have a dataset that indicates whether someone is a person of interest via a boolean 'poi' key. I was able to filter the data with the following:

filtered = []
for n in enron_data:
    if enron_data[n]['poi']: filtered.append(enron_data[n]);
print(len(filtered))

I tried for a while to use pythons built in filter but was unable to. what is a clean way to do this with the builtin filter?

example data: {'METTS MARK': {... 'poi': False,}, ...}

like image 889
devdropper87 Avatar asked Dec 13 '22 23:12

devdropper87


1 Answers

You can use list comprehension to iterate over the dictionary to then create a new list of the values that evaluate True for value['poi'].

filtered = [v for k, v in enron_data.items() if v['poi']]

In fact, you're not using the keys at all, so you could just do:

filtered = [v for v in enron_data.values() if v['poi']]

Or to use filter (similar to @AbidHasan):

filtered = filter(lambda x: x['poi'], enron_data.values())
like image 112
Robert Seaman Avatar answered Jan 08 '23 01:01

Robert Seaman