I'm trying to turn the following code into something more readable.
for x in list_of_dicts:
for y in header:
if y not in x.keys():
x[y] = ''
It takes a list of dictionaries and adds key:value pairs with the default value = '' for any
keys that do not already exist in the current dictionary.
I'm still new to python, so any help would be greatly appreciated. I tried:
return [x[y] = '' for x in list_of_dicts for y in header if y not in x.keys()]
But I'm thinking you can't have "="
This is not a problem you should solve with a list comprehension. You can improve on your existing code using some set operations:
This'll achieve the same effect; add keys from
header
that are missing, as empty strings. For Python 3, replaceviewkeys()
withkeys()
.This makes use of dictionary view objects to give us a set-like views on the dictionary keys; in Python 3 this behaviour is now the default.
If I read your question wrong and
headers
is not a dictionary as well, make it an explicit set to get the same benefits:Using set operations makes the code more readable and efficient, pushing any loops to determine the set difference into optimized C routines.