I have a matrix:
matrix = {
'A' : {
'A1' : {
'A11' : [1,2,3],
'A12' : [4,5,6],
},
'A2' : {
'A21' : [11,12,14],
'A22' : [14,15,16],
},
'A3' : {
'A31' : [111,112,114],
'A32' : [114,115,116],
},
}
}
and I want to retrieve particular paths that are dynamically queried -- such matrix['A']['A2']['A22']
or matrix['A']['A2']
.
In simpler terms, I have a multi-level dictionary, and a list of strings that map to hierarchies in that dictionary. such as ['A','A1','A2']
I'm not sure the most pythonic way of doing this.
The following works. I'm just wondering if there is a more concise or readable way. I'd love another set of eyes to offer input and correct an obvious mistake.
get_target_path( pth , mtx ):
try:
value = mtx
for level in pth :
value = value[level]
return value
except KeyError :
return None
target_path = ['A','A2','A22']
result = get_target_path( target_path , matrix )