简体   繁体   中英

Create unique key list from dictionary array in one-line

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())) )

This should do what you want:

list(set( val for dic in dic_list for val in dic.keys()))

Output:

['grape', 'apple', 'banana']

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM