easy +10 pts

Missing keys default zero

Given a list of dictionaries and a set of keys, sum numeric values where keys are missing, defaulting to zero.

You are given a list of dictionaries, each mapping string keys to integer values. You need to compute the total sum of values for a given set of keys, but if a key is missing from a dictionary, treat its value as 0. Write a function `sum_missing_defaults` that takes a list of dictionaries `data` and a set of keys `keys` and returns the total sum of all values for those keys across all dictionaries. Function signature: `def sum_missing_defaults(data: list[dict], keys: set) -> int:` For example: `data = [{"a": 1, "b": 2}, {"a": 3}]` and `keys = {"a", "b", "c"}`. Summing: from first dict: a=1, b=2, c=0 → 3; from second: a=3, b=0, c=0 → 3; total = 6.

Constraints

Data is a list of 0 to 1000 dictionaries. Each dictionary has string keys and integer values (values can be negative). The set of keys is non-empty (1 to 1000 keys). Total number of key-value pairs across all dictionaries does not exceed 10,000. All keys are strings.

Example

>>> sum_missing_defaults([{"a": 1, "b": 2}, {"a": 3}], {"a", "b", "c"})
6
>>> sum_missing_defaults([], {"x", "y"})
0
>>> sum_missing_defaults([{"x": 5}], {"x", "y"})
5
10 points ~12 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Iterate over each dictionary and each key in the set.
Use the dictionary's `get` method with a default value of 0.
Accumulate the sum in a single integer variable.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.