HappyUnicorn HappyUnicorn - 1 year ago 63
Python Question

Grouping strings from a set to a dictionary python


>>> foo = {("A", "B"), ("A", "G"), ("A", "H"),
... ("B", "C"), ("B", "H"),
... ("C", "D"),
... ("D", "E"), ("D", "G"), ("D", "H"),
... ("E", "F"), ("E", "G"), ("E", "H"),
... ("F", "I"), ("F", "J"), ("F", "K"),
... ("G", "H")}

I am trying to group my set like this, so far I have been unsuccessful, I managed to group them only like this.

Actual output:

>>> {k:set(x[1] for x in v) for k,v in itertools.groupby(sorted(foo), key=lambda x: x[0])}
{'B': {'C', 'H'}, 'E': {'H', 'G', 'F'}, 'D': {'E', 'G', 'H'}, 'A': {'B', 'G', 'H'}, 'C': {'D'}, 'G': {'H'}, 'F': {'I', 'K', 'J'}}

However, this is is my desired output:

foo1 = {"A": {"B", "G", "H"},
"B": {"A", "H", "C"},
"C": {"B", "D"},
"D": {"C", "E", "G", "H"},
"E": {"D", "F", "G", "H"},
"F": {"E", "I", "J", "K"},
"G": {"A", "D", "E", "H"},
"H": {"A", "B", "D", "E", "G"},
"I": {"F"},
"J": {"F"},
"K": {"F"}

I was thinking with permutations or combinations? But I still don't have an idea how to do it.
Thanks in advance.
Edit: Added a picture of how the strings are related.

Answer Source

Something like this ?

foo = {("A", "B"), ("A", "G"), ("A", "H"), ("B", "C"), ("B", "H"), ("C", "D"), ("D", "E"), ("D", "G"), ("D", "H"), ("E", "F"), ("E", "G"), ("E", "H"), ("F", "I"), ("F", "J"), ("F", "K"), ("G", "H")}

from collections import defaultdict

result = defaultdict(set)

for key1, key2 in foo:

from pprint import pprint

Which, contrary to the other answers so far, produces the desired output, albeit unordered:

{'A': {'B', 'G', 'H'},
'B': {'A', 'C', 'H'},
'C': {'B', 'D'},
'D': {'G', 'C', 'H', 'E'},
'E': {'G', 'D', 'H', 'F'},
'F': {'I', 'J', 'K', 'E'},
'G': {'A', 'D', 'H', 'E'},
'H': {'B', 'A', 'G', 'D', 'E'},
'I': {'F'},
'J': {'F'},
'K': {'F'}}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download