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,}, ...}
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With