Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the intersection of the keys of dictionaries

I'm trying to write a one liner function using map, filter, reduce that takes is a list of dictionaries (Ld) and returns a collection of the keys that are contained in all the dictionaries (the intersection of the keys).

The function below attempts to do this. The map portion returns a collection of True/False if the key is in a particular dictionary. The reduce returns True if all of such elements are true. Lastly, the filter portion filters out all the keys that don't satisfy such conditions.

def intersection_of_keys(Ld):
    return filter(lambda key: reduce(lambda x, y: x*y, map(lambda dic: key in dic, Ld)), all_keys(Ld))

#For example:  
d1 = {1:12, 3:4, 2:5}  
d2 = {1:6, 3:8, 0:9}  
d3 = {3:0, 1:11, 2:3}  
Ld = [d1, d2, d3]  
print(intersection_of_keys(Ld))  

The code should print a collection containing 1 and 3. But the variable key inside the map portion is undefined. Any ideas why key is not passed into the lambda function definition for the map? And any ideas of how to work around this?

like image 911
pip1726 Avatar asked Mar 05 '23 14:03

pip1726


1 Answers

filter, reduce, map, and lambda... oh my! This is Python, remember, so don't make this harder than it needs to be. Just using a good ol' for-loop:

>>> keys, *morekeys = [d.keys() for d in Ld]
>>> for k in morekeys: 
...     keys &= k 
...
>>> keys
{1, 3}

If you insist on using reduce, it's like this:

>>> from functools import reduce
>>> from operator import and_
>>> reduce(and_, [d.keys() for d in Ld])
{1, 3}
like image 111
wim Avatar answered Mar 15 '23 20:03

wim