Extract all keys from a list of dictionaries
Solution 1:
all_keys = set().union(*(d.keys() for d in mylist))
Edit: have to unpack the list. Now fixed.
Solution 2:
Your data:
>>> LoD
[{'age': 10, 'name': 'Tom'},
{'age': 5, 'name': 'Mark', 'height': 4},
{'age': 7, 'name': 'Pam', 'weight': 90}]
This set comprehension will do it:
>>> {k for d in LoD for k in d.keys()}
{'age', 'name', 'weight', 'height'}
It works this way. First, create a list of lists of the dict keys:
>>> [list(d.keys()) for d in LoD]
[['age', 'name'], ['age', 'name', 'height'], ['age', 'name', 'weight']]
Then create a flattened version of this list of lists:
>>> [i for s in [d.keys() for d in LoD] for i in s]
['age', 'name', 'age', 'name', 'height', 'age', 'name', 'weight']
And create a set to eliminate duplicates:
>>> set([i for s in [d.keys() for d in LoD] for i in s])
{'age', 'name', 'weight', 'height'}
Which can be simplified to:
{k for d in LoD for k in d.keys()}