You receive orders as a list of dictionaries and need a quick channel mix breakdown for the daily standup.
Write a function count_by_channel(orders) that returns a dictionary mapping each channel value to the number of orders that used it.
This fixture runs before your code on every Run and Submit, so the data is always clean.
orders = [
{"order_id": 1, "channel": "UPI", "amount": 820},
{"order_id": 2, "channel": "Card", "amount": 2450},
{"order_id": 3, "channel": "UPI", "amount": 310},
{"order_id": 4, "channel": "COD", "amount": 999},
{"order_id": 5, "channel": "UPI", "amount": 1500},
{"order_id": 6, "channel": "Card", "amount": 640},
]- Step 1: Start with an empty dictionary that will hold one entry per channel.
- Step 2: Loop the orders and read `order["channel"]` — the grouping key.
- Step 3: `counts.get(channel, 0) + 1` reads the running count, defaulting to `0` the first time a channel appears, so there is no `KeyError`.
- Step 4: Return the dictionary. `collections.Counter([o["channel"] for o in orders])` is the one-line equivalent interviewers like to see as a follow-up.
def count_by_channel(orders):
counts = {}
for order in orders:
channel = order["channel"]
counts[channel] = counts.get(channel, 0) + 1
return countsLearn the concept first
Stuck on Dictionaries? These free Python lessons teach it step by step.
More Dictionaries questions
- This is the only question on this topic for now.
Practising alone only goes so far — our live cohorts pair Python and Pandas depth with dashboards, agentic analytics projects and mock interviews.
Explore the program