Created
February 6, 2021 12:50
-
-
Save gidgid/252c05645fc798002229617e3f3f5373 to your computer and use it in GitHub Desktop.
shows how to use map_reduce to summarize specific properties on values
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 dataclasses import dataclass | |
from typing import Iterable, Tuple, Dict, Set | |
from more_itertools import map_reduce | |
@dataclass(frozen=True, eq=True) | |
class Order: # 1 | |
order_id: str # 1 | |
price: int # 1 | |
def map_order_id_to_highest_price(orders: Iterable[Order]) -> Dict[str, int]: | |
return map_reduce( | |
orders, | |
keyfunc=lambda order: order.order_id, # 2 | |
valuefunc=lambda order: order.price, # 3 | |
reducefunc=max, # 4 | |
) | |
def test_group_edges_by_source_node(): | |
orders = { | |
Order(order_id="123", price=4), | |
Order(order_id="456", price=4), | |
Order(order_id="123", price=3), | |
Order(order_id="456", price=10), | |
Order(order_id="123", price=6), | |
Order(order_id="789", price=7), | |
} | |
order_id_to_higest_price = map_order_id_to_highest_price(orders) | |
assert order_id_to_higest_price == {"123": 6, "456": 10, "789": 7} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment