This is not a problem you should solve with a list comprehension. You can improve on your existing code using some set operations:
for x in list_of_dicts:
x.update((y, '') for y in header.viewkeys() - x)
This'll achieve the same effect; add keys from header
that are missing, as empty strings. For Python 3, replace viewkeys()
with keys()
.
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:
header_set = set(header)
for x in list_of_dicts:
x.update((y, '') for y in header_set.difference(x))
Using set operations makes the code more readable and efficient, pushing any loops to determine the set difference into optimized C routines.