Filter dictionary if key value is true
I am completely new to Python (1st day). I have a dataset that indicates if someone is an interested person using the boolean key "poi". I managed 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 the pythons built into the filter, but couldn't. what is the clean way to do it with a built in filter?
example data: {'METTS MARK': {... 'poi': False,}, ...}
+3
source to share
4 answers
You can use a list comprehension to iterate over a dictionary to then create a new list of values ββto evaluate True
for value['poi']
.
filtered = [v for k, v in enron_data.items() if v['poi']]
In fact, you are not using keys at all, so you can simply do:
filtered = [v for v in enron_data.values() if v['poi']]
Or use a filter (similar to @AbidHasan):
filtered = filter(lambda x: x['poi'], enron_data.values())
+4
source to share