rohit
rohit

Reputation: 31

Searching for elements in a python list

Searching for elements in a python list and then accessing particular values

Mylist = [('A',3,['x','y','z']),('B',2,['m','n'])]  

Variable = 'A'  

i = Mylist.index(Variable)  
print i  

For example I would like to check if is Variable is present and access its elements like is present then access each of sublist elements one by one

For instance in the above example I would like to check if 'A' is present and if yes then get access to its individual sublist elements like 'x' , 'y' and 'z'

Upvotes: 3

Views: 349

Answers (4)

eyquem
eyquem

Reputation: 27565

Mylist = [('A',3,['x','y','z']),('B',2,['m','n']),
          ('C',5,['r','p','u']),('A',10,['k','X']),
          ('E',8,['f','g','h','j'])]

for i,(a,b,c) in enumerate(Mylist):
    if a=='A':
        print i,c

result

0 ['x', 'y', 'z']
3 ['k', 'X']

Upvotes: 0

wapcaplet
wapcaplet

Reputation: 1

As others have said, a dict is really the appropriate data type to use when you need to index things by arbitrary data types (like strings). With nested sequences, there's no guarantee that your 'index' (the 'A' and 'B' in this case) will be unique, and some extra contortion is needed to look up values. Also as others have said, the ['x', 'y', 'z'] part will remain in order, regardless of whether it's a list-in-a-tuple-in-a-list, or a list-in-a-dict.

That said, the easiest way I can think of to find the tuple you want without using a dict is:

indices = zip(*Mylist)[0]   # ('A', 'B')
index = indices.index('A')  # 0
result = Mylist[index]      # ('A', 3, ['x', 'y', 'z'])

To get at the sublist, use its index:

sublist = result[2]

or unpack it:

lookup, length, sublist = result

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

It looks like you haven't found the Python dict yet. Perhaps you mean:

mydict = {}
mydict['A'] = {'count': 3, 'letters': ['x','y','z']}
mydict['B'] = {'count': 2, 'letters': ['m','n']}

mydict is a dictionary that itself contains dictionaries.

You can then look them up with:

val = mydict['A']
print val['letters']

Of course, there's little point in storing 'count' since you can just use len() if you need to. You could do it like so:

mydict = {'A': ['x','y','z'], 'B': ['m','n']}
print mydict['A']

Upvotes: 1

Andrew White
Andrew White

Reputation: 53496

You just need to use a dictionary...

myDict = dict([('A',3,['x','y','z']),('B',2,['m','n'])])
if 'A' in myDict:
    val = myDict['A']

Upvotes: 0

Related Questions