Created
February 6, 2021 12:38
-
-
Save gidgid/14ffb5fc19a9bc08f752cc248cec977c to your computer and use it in GitHub Desktop.
shows how to create a multivalue dict from tuples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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