Aaron
Aaron

Reputation: 165

How to remove the entire dictionary from a list of dictionaries if a specific key is empty?

So I have a list of dictionaries which has a lot of entries and looks something like that:

[{'Date': 'Jul 26', 'Time': '07:04:12', 'PID': '28886', 'Message': 'authentication failure; logname= uid=0 euid=0 tty=NODEVssh ruser= rhost=207.243.167.114  user=root', 'Access Type': 'Failed', 'host/IP address': '207.243.167.114'}
{'Date': 'Jul 27', 'Time': '04:16:07', 'PID': '30999', 'Message': 'session opened for user cyrus by (uid=0)', 'Access Type': 'Success', 'host/IP address': ''}
{'Date': 'Jul 27', 'Time': '04:16:08', 'PID': '30999', 'Message': 'session closed for user cyrus', 'Access Type': '', 'host/IP address': ''}]

I want to remove the entire dictionary where "Access Type" == ''

I've tried this but this removes all the dictionaries as long as the value is blank in it but i only want specifically for "Access Type"

[d for d in data if all(d.values())]

Upvotes: 0

Views: 43

Answers (1)

RoadRunner
RoadRunner

Reputation: 26315

You could use a list comprehension to check if Access Type is not empty:

[d for d in data if d["Access Type"]]

Or checking explicitly against "":

[d for d in data if d["Access Type"] != ""]

The first one works because empty strings "" are considered False in a truth testing context. You can have a look at Truth Value Testing from the documentation for more information.

Upvotes: 1

Related Questions