How to refence entries with a certain value within a list in python

Tags: , ,

I am getting data from database and storing it in a list called relays. this list currently looks like this:

 relay:  [(4, '26', '19'), (5, '13', '6')]

the first number of each item is the id number I use through out the code. the second two are numbers GPIO pins .

I want a away to reference the list item by it’s first number so for instance variable[5][1] which would return 13. so to turn on this GPO pin I can just run something like:

GPIO.output(variable[5][1], True)
GPIO.output(variable[4][2], True)

Is this possible? (sorry if this is a stupid question, I am new to python)


You can create a dict with first value of tuple as a key and the whole tuple as value:

relay =  [(4, '26', '19'), (5, '13', '6')]

# desired = {4: (4, '26', '19'), 5: (5, '13', '6')} 

# dict with first tup val as key and the whole tup as val
variable = {x[0]: (x) for x in relay}  


# print the dict with key `5` and then the first (1) index val of tup


{4: (4, '26', '19'), 5: (5, '13', '6')}                                                                                                                                      

Source: stackoverflow