Make sure all dicts in a list have the same keys

dictionary, list, python, set

Solution

>>> from itertools import chain 
>>> l = [{'x': 42}, {'x': 23, 'y': 5}]
>>> all_keys = set(chain.from_iterable(l))   
>>> for d in l:
        d.update((k,None) for k in all_keys-d.viewkeys())


>>> l
[{'y': None, 'x': 42}, {'y': 5, 'x': 23}]

Problem

I have a list with dictionaries like ``` [{'x': 42}, {'x': 23, 'y': 5}] ``` and want to make sure all dicts have the same keys, with values of `None` if the key was not present in the original dict. So the list above should become ``` [{'x': 42, 'y': None}, {'x': 23, 'y': 5}] ``` What's the most beautiful and pythonic way to do this? Current approach: ``` keys = reduce(lambda k, l: k.union(set(l)), [d.keys() for d in my_list], set()) new_list = [dict.fromkeys(keys, None) for i in xrange(len(my_list))] for i, l in enumerate(my_list): new_list[i].update(l) ``` But especially the first two lines seem kind of clumsy. Ideas?

Original source