I have a 2D list where each “row” has an index, name, and a path like [(1L, "bar", "foo/bar"), (2L, "app", "some/app"),] etc. I am trying to retrieve a “row” from this 2D list given and index. For example, an index of 1 should return (1L, "bar", "foo/bar"). I know I can loop through my whole list and compare the index until I find the object like so:
my_index = 1
for row in my_list:
if (row[0] == my_index)
return row
return False
I was wondering if there is a cleaner/nicer way to do this in python, since I am new to python. I know there is an index method for a list that returns the index from a list but I’m not sure how I can use that with a 2D list. Thanks in advance! Oh and also, it can be assumed that there will only be one instance of each object (i.e: no duplicates)
It looks like you would be better off using a dictionary instead of a list, so your data would look like this:
This allows you to efficiently access each element by index:
Here is how you could create the dictionary from the list:
Or on Python 2.6 and below: