简体   繁体   中英

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())]

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM