Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python finding pairs, same values

This might be a simple problem for somebody else, but it is difficult for me right now. I have this dictionary:

{
  "first": {"a", "b"},
  "second": {"a", "c"},
  "third": {"b"}, 
  "fourth": {"b"},
  "fifth": {"c"},
}

What I am trying to do is arrange this into a new dictionary which contains sets and inside of those sets pairs of keys. Example:

{("first", "second"),("first", "third"), ("first", "fourth"), ("second", "fifth")}

First pair would be first and second, because both have "a", second pair would be first and third because they both contain "b" and so on...

My idea was to take the first key and compare it with the rest and store result in set, do the next one... But I can't seem to get the logic down. Do you guys have any tips hints on what I should do?

like image 577
zero set Avatar asked Jan 01 '23 13:01

zero set


1 Answers

Solvable with a single line. combinations(d.keys(), 2) creates pairs of keys, then we use a set comprehension to keep the pairs of keys whose values have a non-empty intersection.

from itertools import combinations

d = {
  "first": {"a", "b"},
  "second": {"a", "c"},
  "third": {"b"},
  "fourth": {"b"},
  "fifth": {"c"},
}

print({(key1, key2) for key1, key2 in combinations(d.keys(), 2) if d[key1] & d[key2]})
# {('first', 'third'), ('third', 'fourth'), ('second', 'fifth'),
#  ('first', 'fourth'), ('first', 'second')}
like image 108
DeepSpace Avatar answered Jan 04 '23 02:01

DeepSpace