Write a Python function that uses a dictionary to sum the 'amount' field per 'customer_id', skipping any None values.
1Times asked
Nov 2026Last seen
Nov 2026First seen
💡 Model Answer
You can iterate over the list of orders and use a dictionary where the key is the customer_id and the value is the running total. Skip any order whose amount is None. Example:
python
orders = [
{'customer_id': 1, 'amount': 100},
{'customer_id': 2, 'amount': None},
{'customer_id': 1, 'amount': 50},
]
totals = {}
for order in orders:
cid = order['customer_id']
amt = order['amount']
if amt is None:
continue
totals[cid] = totals.get(cid, 0) + amt
print(totals) # {1: 150}The algorithm runs in O(n) time and O(k) space, where n is the number of orders and k is the number of distinct customer_ids.
This answer was generated by AI for study purposes. Use it as a starting point — personalize it with your own experience.
🎤 Get questions like this answered in real-time
Assisting AI listens to your interview, captures questions live, and gives you instant AI-powered answers on a discreet on-screen overlay.
Get Assisting AI — Starts at ₹500