Suppose I have a python dictionary with the following structure:
data = {
"key_1": "some value",
"key_2": "some value",
"key_3": "",
"key_4": ""
}
So, I want to remove all key-values for which the value is an empty string. I could use the python one in the following way:
for key in list(data.keys()):
if data[key] == "":
del data[key]
Or I could build a new dictionary with a comprehension:
new_ dict = {
key: value
for key, value in data.items()
if value != ""
}
Both solutions are very readable, but which is more efficient and why?