Region by Product

Data with PythonHard+10 XP+10

Region by Product

An online tea shop wants a grid of how many orders came from each region for each product. Orders only store a customer number, and the regions are in a separate customer list. Some orders come from guest customers who aren't in that list, and those orders must still be counted.

Task: write region_product_counts(orders, customers).

  • orders is a dictionary of two lists, "customer_id" and "product", one entry per order. There is at least one order.
  • customers is a dictionary of two lists, "customer_id" and "region". Each customer number appears once. No region is called "Unknown".
  • An order whose customer number isn't in customers belongs to the region "Unknown".

Return a dictionary with two keys:

  • "products": every product that was ordered, sorted alphabetically.
  • "rows": one list per region that has at least one order. Each list is [region, count for each product..., total], with the counts in the same order as "products" and total the region's number of orders. A region with no orders of a product has 0 there. All counts are ints.

Sort the rows by total, biggest first. If two regions have the same total, put them in alphabetical order.

Examples

orders = {"customer_id": [1, 2, 1, 3, 9, 2], "product": ["green", "black", "black", "green", "green", "green"]}
customers = {"customer_id": [1, 2, 3], "region": ["North", "South", "North"]}
returns {'products': ['black', 'green'], 'rows': [['North', 1, 2, 3], ['South', 1, 1, 2], ['Unknown', 0, 1, 1]]}
orders = {"customer_id": [5, 6], "product": ["mint", "mint"]}
customers = {"customer_id": [5, 6, 7], "region": ["West", "East", "West"]}
returns {'products': ['mint'], 'rows': [['East', 1, 1], ['West', 1, 1]]}

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run