python: union keys from multiple dictionary?

后端 未结 5 801
终归单人心
终归单人心 2021-02-12 20:49

I have 5 dictionaries and I want a union of their keys.

alldict =  [dict1, dict2, dict3, dict4, dict5]

I tried

allkey = reduce(         


        
5条回答
  •  星月不相逢
    2021-02-12 21:05

    A simple strategy for non-functional neurons (pun intended):

    allkey = []
    
    for dictio in alldict:
        for key in dictio:
            allkey.append(key)
    
    allkey = set(allkey)
    

    We can convert this code to a much sorter form using set comprehensions:

    allkey = {key for dictio in alldict for key in dictio}
    

    This one-liner is still very readable in comparison with the conventional for loop. The key to convert a nested loop to a list or set comprehension is to write the inner loop (the one that varies faster in the nested loop) as the last index (that is, for key in dictio).

提交回复
热议问题