python: union keys from multiple dictionary?

后端 未结 5 796
终归单人心
终归单人心 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 20:53

    Your solution works for the first two elements in the list, but then dict1 and dict2 got reduced into a set and that set is put into your lambda as the x. So now x does not have the method keys() anymore.

    The solution is to make x be a set from the very beginning by initializing the reduction with an empty set (which happens to be the neutral element of the union).

    Try it with an initializer:

    allkey = reduce(lambda x, y: x.union(y.keys()), alldict, set())
    

    An alternative without any lambdas would be:

    allkey = reduce(set.union, map(set, map(dict.keys, alldict)))
    

提交回复
热议问题