Solution 1

``````def number_of_customers_per_state(customers_dict):
results = {}
for state, customers in customers_dict.items():
if customers:
results[state] = len(customers)
else:
results[state] = 0
return results``````

Number of customers per state

Customers are expressed as a dictionary, divided by state. Each key represents a state. Example:

``````customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': [{
'name': 'Linda',
'age': 71
}],
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
``````

Each state contains a list with all the customers. A single customer is represented as a dictionary with only two keys, `name` and `age`.

Write a function `number_of_customers_per_state` that receives a `customers` dictionary and calculates the number of customers per state. The result will be a new dictionary, with each key containing a state and the count as the associated value.

Example:

``````customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': [{
'name': 'Linda',
'age': 71
}],
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
result = number_of_customers_per_state(customers)
print(result)
``````

Prints:

``````expected_result = {
'UT': 3,
'NY': 1,
'CA': 2
}
``````

Test Cases

test number of customers per state -

``````def test_number_of_customers_per_state():
"""Should return the correct number of customers per state."""
customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': [{
'name': 'Linda',
'age': 71
}],
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
expected_result = {
'UT': 3,
'NY': 1,
'CA': 2
}
assert number_of_customers_per_state(customers) == expected_result
``````

test number of customers per state with blank state -

``````def test_number_of_customers_per_state_with_blank_state():
"""Should return the correct number of customers per state."""
customers = {
'UT': [{
'name': 'Mary',
'age': 28
}, {
'name': 'John',
'age': 31
}, {
'name': 'Robert',
'age': 16
}],
'NY': None,  # Be Careful! NY value is None
'CA': [{
'name': 'Barbara',
'age': 15
}, {
'name': 'Paul',
'age': 18
}]
}
expected_result = {
'UT': 3,
'NY': 0,
'CA': 2
}
assert number_of_customers_per_state(customers) == expected_result
``````
def number_of_customers_per_state(customers_dict): pass