Home > Back-end >  Finding the intersection of value pairs in a dictionary in python?
Finding the intersection of value pairs in a dictionary in python?

Time:11-09

I have a dictionary in python that looks like this:

x = {'a' : [27, 6, 8, 5],
'b': [27, 9, 8, 2],
'c': [27, 9, 8, 6]}

I want to write a function that will take the second values (the value pairs) of each item, then returns the intersection of all 3 of them. So I'd want the output to be:

`[27, 8]`

How could I do this?

CodePudding user response:

We iterate over the values of the dict, convert them to sets as we go and intersect all of them to get the result you want.

x = {'a': [27, 6, 8, 5],
     'b': [27, 9, 8, 2],
     'c': [27, 9, 8, 6]}

for n, items in enumerate(x.values()):
    if n == 0:
        common = set(items)
    else:
        common &= set(items) # Equivalent to `common = common.intersection(items)`.
print(common)
# {8, 27}

CodePudding user response:

Using set intersection:

>>> set.intersection(*map(set, x.values()))
{8, 27}

CodePudding user response:

You can convert dictionary values to a set then use & the intersection operator.

x = {'a' : [27, 6, 8, 5],
'b': [27, 9, 8, 2],
'c': [27, 9, 8, 6]}

output = list(set(x['a']) & set(x['b']) & set(x['c']))

print (output)

[Result]

[8, 27]

CodePudding user response:

If you want rowvise common elements, this should do the trick

def commons(mat):
    res = []
    
    mp = dict()
    for j in range(len(mat[0])):
        mp[mat[0][j]] = 1
 
    for i in range(1, len(mat)):
        for j in range(len(mat[0])):
            if (mat[i][j] in mp.keys() and
                             mp[mat[i][j]] == i):
                                  
                mp[mat[i][j]] = i   1
 
                if i == len(mat) - 1:
                    res.append(mat[i][j])

    return res
    
x = {'a' : [27, 6, 8, 5],
'b': [27, 9, 8, 2],
'c': [27, 9, 8, 6]}

A = list(x.values())

print(commons(A))

-> [27, 8]

Taken from https://www.geeksforgeeks.org/common-elements-in-all-rows-of-a-given-matrix/

CodePudding user response:

I am unsure what you mean when you say "intersection", but if you would like to compare the 2nd value of each sublist, you would do:

a_second = x['a'][1]
b_second = x['b'][1]
c_second = x['c'][1]

Please be more specific with what you are trying to do with these values.

  • Related