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


You can also use the function filter

.



new_list = filter(lambda x: a[x]['POI'], a)

      

+1


source


Another function filter

new_list = filter(your_dict.get, your_dict)

      

Less expensive than using lambda

inside a function filter

.

0


source


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)

      

0


source







All Articles