Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: union keys from multiple dictionary?

Tags:

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.

like image 929
Tg. Avatar asked Mar 09 '11 06:03

Tg.


People also ask

How do you pass multiple dictionary parameters in Python?

Use *args to take multiple arguments. Show activity on this post. Show activity on this post. If you want to avoid combining the dictionaries, then provide them as arguments rather than keyword arguments, and set their defaults to something (such as None ), and convert None to {} and otherwise copy the dictionary.

Can you concatenate dictionaries in Python?

In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.

What Python method is used to get all the keys from a dictionary?

Python Dictionary keys() method The keys() method in Python Dictionary, returns a view object that displays a list of all the keys in the dictionary in order of insertion using Python.


2 Answers

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.

like image 140
Duncan Avatar answered Sep 19 '22 12:09

Duncan


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)))
like image 32
chuck Avatar answered Sep 18 '22 12:09

chuck