3

Python 2.7

data structure is like this,

hitdict = {'A':[1,2,3,4], 'B':[2,3,6,5], 'C':[2,3,7,8]}

Note the number of key:value pairs is variable. I want the intersection of A, B, C :

[2,3]

For intersection of two or more list, most answers suggest either set class or lambda functions. eg. intersection of lists of list, using lambda functions

and from a previous question, where a,b,c are lists

>> set(a) & set(b) & set(c)

I have a number of dictionaries like this with variable number of lists.

My main confusion is about how to use the above set(), since if I use for loop with hitdict.items() it will give k:v pairs only one at a time. Hence the code below is incorrect.

for (k,v) in hitdict.items():
    common = set(hitdict[k]) + set(hitdict[k+1])

How to do this in Python ?

Community
  • 1
  • 1
le_llama
  • 143
  • 1
  • 10
  • I started out 3 months back with python, hence the inability to understand and adopt the answer from Duplicate question. – le_llama Aug 17 '15 at 11:34
  • In case more than one answer works, what is the basis to decide which one to accept ? – le_llama Aug 17 '15 at 11:48
  • Generally you should accept an answer that helps you most (post your own if none of the answers are satisfactory). Since you've already marked one as accepted, let it be; you can upvote the others to show appreciation. Check http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Anshul Goyal Aug 17 '15 at 17:56

3 Answers3

3

Use map to convert lists to sets and reduce to apply the intersection. Do:

reduce(lambda x,y: x&y, map(set, hitdict.values()))

It gives:

set([2, 3])
Assem
  • 11,574
  • 5
  • 59
  • 97
2

You can use reduce, with a custom lambda and set intersection to do that:

>>> hitdict = {'A':[1,2,3,4], 'B':[2,3,6,5], 'C':[2,3,7,8]}
>>> reduce(lambda x, y: x.intersection(y), (set(x) for x in hitdict.values()))
set([2, 3])

Note that the generator above also ensures that your items are fed one by one to reduce.

Anshul Goyal
  • 73,278
  • 37
  • 149
  • 186
1

You can do something like:-

reduce(lambda value1, value2: set(value1).intersection(set(value2)), hitdict.values())
hspandher
  • 15,934
  • 2
  • 32
  • 45