Skip to content

Instantly share code, notes, and snippets.

@gidgid
Created February 6, 2021 12:38
Show Gist options
  • Save gidgid/14ffb5fc19a9bc08f752cc248cec977c to your computer and use it in GitHub Desktop.
Save gidgid/14ffb5fc19a9bc08f752cc248cec977c to your computer and use it in GitHub Desktop.
shows how to create a multivalue dict from tuples
from typing import Iterable, Tuple, Dict, Set
from more_itertools import map_reduce
def group_edges(edges: Iterable[Tuple[str, str]]) -> Dict[str, Set[str]]:
return map_reduce(
edges,
keyfunc=lambda edge: edge[0], # 1
valuefunc=lambda edge: edge[1], # 2
reducefunc=set, # 3
)
def test_group_edges_by_source_node():
edges = [
("n1", "n2"),
("n2", "n3"),
("n1", "n3"),
("n1", "n2"),
("n3", "n4"),
("n1", "n4"),
("n2", "n4"),
]
actual_grouping = group_edges(edges)
expected_grouping = {"n1": {"n2", "n3", "n4"}, "n2": {"n3", "n4"}, "n3": {"n4"}}
assert actual_grouping == expected_grouping
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment