Accessing multidimensional lists with an index list

Gabriel Birke gabriel.birke at gmail.com
Sun Apr 17 15:50:58 EDT 2005


Given the multidimensional list l:
l = [ {'v1': 1, 'v2': 2},
	  [ {'v1':4, 'v2': 7},
	    {'v1': 9, 'v2': 86},
		[ {'v1': 77, 'v2': 88}]
	  ]
	 ]

I want to access specific items the indices of which are stored in
another list. For now, I created a function to do this:

def getNestedValue(l, indices):
	while len(indices) > 0:
		i = indices.pop(0)
		l = l[i] #In future versions, put error checking here
	return l

print getNestedValue(l, [1, 2, 0])
print getNestedValue(l, [1, 1])

Is there a more elegant or performant language construct to accomplish
my task?



More information about the Python-list mailing list