Create a single key list in the single-line dictionary table

advertisements

I have a code like below. Although it works, I want to know more compact implementation. Is it possible to implement this code as one or two liners?

all_keys = []
dic_list = [{'apple': None, 'banana': None}, {'grape': 1, 'apple':None}]
for d in dic_list:
    for k in d.keys():
        if k not in all_keys: all_keys.append(k)
print(all_keys) # ['apple', 'banana', 'grape'] all unique keys


Simply use set.union across the dictionaries:

>>> set().union(*dic_list)
{'apple', 'banana', 'grape'}

This approach is much faster than a double loop (such as set( val for dic in dic_list for val in dic.keys())))