Reputation: 4083
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
Upvotes: 0
Views: 86
Reputation: 549
From the question, my inference is a shorter implementation which prints the keys in sorted manner.
dic_list = [{'apple': None, 'banana': None}, {'grape': 1, 'apple':2}]
all_keys = sorted({k for d in dic_list for k in d.keys()})
print(all_keys)
We can use python's powerful List/Set/Dictionary comprehensions to achieve this with relatively fewer lines of code.
Hope this helps.
Upvotes: 0
Reputation: 8829
You could use a set (marked by curly braces {}
), which enforces that elements are not repeated:
all_keys = {k for d in dic_list for k in d.keys()}
# {'apple', 'banana', 'grape'}
This strategy is more efficient than looping, and the intent is much clearer.
Upvotes: 1
Reputation: 23176
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()))
)
Upvotes: 3
Reputation: 4396
This should do what you want:
list(set( val for dic in dic_list for val in dic.keys()))
Output:
['grape', 'apple', 'banana']
Upvotes: 2