python: union keys from multiple dictionary?

Tg. picture Tg. · Mar 9, 2011 · Viewed 15.2k times · Source

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

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

I tried

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

but it gave me an error

AttributeError: 'set' object has no attribute 'keys'

Am I doing it wrong ? I using normal forloop but I wonder why the above code didn't work.

Answer

Duncan picture Duncan · Mar 9, 2011

I think @chuck already answered the question why it doesn't work, but a simpler way to do this would be to remember that the union method can take multiple arguments:

allkey = set().union(*alldict)

does what you want without any loops or lambdas.