Let's write our own getnesteditem
and setnesteditem
:
def getnesteditem(xs, path):
for i in path:
xs = xs[i]
return xs
def setnesteditem(xs, path, newvalue):
for i in path[:-1]:
xs = xs[i]
xs[path[-1]] = newvalue
And try it with your list of indices a = [3,4,1]
:
a = [3, 4, 1]
b = [[[15*i+3*j+k for k in range(3)] for j in range(5)] for i in range(4)]
print(*b, sep='\n')
# [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]
# [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]
# [[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]]
# [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, 58, 59]]
print(getnesteditem(b, a))
# 58
setnesteditem(b, a, -9)
print(*b, sep='\n')
# [[ 0, 1, 2], [ 3, 4, 5], [ 6, 7, 8], [ 9, 10, 11], [12, 13, 14]]
# [[15, 16, 17], [18, 19, 20], [21, 22, 23], [24, 25, 26], [27, 28, 29]]
# [[30, 31, 32], [33, 34, 35], [36, 37, 38], [39, 40, 41], [42, 43, 44]]
# [[45, 46, 47], [48, 49, 50], [51, 52, 53], [54, 55, 56], [57, -9, 59]]
b[*a] = 'foo'
didn't know to unpack the arguments for dictionary traversal... – Deadeye