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?
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')}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With