I’m trying to define a function that will allow me to get a value count at various levels of a dict. For example, if I have something like:
vehicles = {
'Ford': {
'Falcon': {
'2008': 10,
'2009': 12,
'2010': 5
}
},
'Holden': {
'Commodore': {
'2008': 15,
'2009': 11,
'2010': 5
}
}
}
I’d like to be able to call a function that will calculate the values at each depth. So at depth 0, the function would return the sum of every value (58). At depth 1, the function would return a dict with {'Ford': 27, 'Holden': 31}. At depth 2, the function would return a dict with {'Ford': {'Falcon': 27}, 'Holden': {'Commodore': 31}}. Etc…
I think I need to burrow to the max depth and start summing the values as I move back up the levels, but I’m fairly new to Python and I’m struggling. Possibly I would need to use recursion?
Thanks for your help.
My solution, not thoroughly tested
TEST: