I have this list of dictionaries and I need to get the sum of all the values inside it.
warehouses = {
"Warehouse Lisboa": [
{ "name": "apples", "tons": 4},
{ "name": "oranges", "tons": 10},
{ "name": "lemons", "tons": 50}
],
"Warehouse Cascais": {
"Branch 1": [
{ "name": "apples", "tons": 10},
{ "name": "oranges", "tons": 24}
],
"Branch 2": [
{ "name": "apples", "tons": 16},
{ "name": "oranges", "tons": 8}
]
},
"Warehouse Oeiras": {
"Branch 1": {
"Sub Branch 1":{
"Sub sub Branch 1": [
{ "name": "lemons", "tons": 10}
]
}
},
"Branch 2": [
{ "name": "apples", "tons": 3}
]
}
}
I tried this:
def stock_fruits(warehouses):
return sum(warehouses.values())
but it gave error:
TypeError: unsupported operand type(s) for : 'int' and 'list'
CodePudding user response:
Consider using a depth-first search approach:
from typing import Union
def stock_fruits(curr: Union[dict, list]) -> int:
if isinstance(curr, dict):
return sum(stock_fruits(value) for value in curr.values())
return sum(entry["tons"] for entry in curr)
warehouses = {
"Warehouse Lisboa": [
{"name": "apples", "tons": 4},
{"name": "oranges", "tons": 10},
{"name": "lemons", "tons": 50}
],
"Warehouse Cascais": {
"Branch 1": [
{"name": "apples", "tons": 10},
{"name": "oranges", "tons": 24}
],
"Branch 2": [
{"name": "apples", "tons": 16},
{"name": "oranges", "tons": 8}
]
},
"Warehouse Oeiras": {
"Branch 1": {
"Sub Branch 1": {
"Sub sub Branch 1": [
{"name": "lemons", "tons": 10}
]
}
},
"Branch 2": [
{"name": "apples", "tons": 3}
]
}
}
print(f"{stock_fruits(warehouses) = }")
Output:
stock_fruits(warehouses) = 135
CodePudding user response:
You can use this function to compute the sum:
def stock_fruits(warehouses):
fruit_sum = 0
queue = deque(list(warehouses.values()))
while queue:
node = queue.popleft()
if isinstance(node, List):
fruit_sum = sum([item.get('tons', 0) for item in node])
else:
queue.extend(list(node.values()))
return fruit_sum