Reputation: 4187
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,}, ...}
Upvotes: 8
Views: 12265
Reputation: 29
d = {1:11, 2:22, 3:33}
# filter by value
d3 = {}
for key,value in d.items():
if value in [22,33]:
d3.update({key:value})
print(d3)
Upvotes: 0
Reputation: 1908
Another filter
function
new_list = filter(your_dict.get, your_dict)
Less expensive than using lambda
inside the filter
function.
Upvotes: 4
Reputation: 2582
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())
Upvotes: 12
Reputation: 658
You could also use the filter
function.
new_list = filter(lambda x: a[x]['POI'], a)
Upvotes: 1