I\'m trying to get a list of all keys in a list of dictionaries in order to fill out the fieldnames argument for csv.DictWriter.
previously, I had something like thi
Borrowing lis from @AshwiniChaudhary's answer, here is an explanation of how you could solve your problem.
>>> lis=[
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5, "height":4},
{"name": "Pam", "age": 7, "weight":90}
]
Iterating directly over a dict returns its keys, so you don't have to call keys() to get them back, saving a function call and a list construction per element in your list.
>>> {k for d in lis for k in d}
set(['age', 'name', 'weight', 'height'])
or use itertools.chain:
>>> from itertools import chain
>>> {k for k in chain(*lis)}
set(['age', 'name', 'weight', 'height'])