I am getting data from database and storing it in a list called relays. this list currently looks like this:
JavaScript
x
2
1
relay: [(4, '26', '19'), (5, '13', '6')]
2
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:
JavaScript
1
3
1
GPIO.output(variable[5][1], True)
2
GPIO.output(variable[4][2], True)
3
Is this possible? (sorry if this is a stupid question, I am new to python)
Advertisement
Answer
You can create a dict with first value of tuple as a key and the whole tuple as value:
JavaScript
1
12
12
1
relay = [(4, '26', '19'), (5, '13', '6')]
2
3
# desired = {4: (4, '26', '19'), 5: (5, '13', '6')}
4
5
# dict with first tup val as key and the whole tup as val
6
variable = {x[0]: (x) for x in relay}
7
8
print(variable)
9
10
# print the dict with key `5` and then the first (1) index val of tup
11
print(variable[5][1])
12
OUTPUT:
JavaScript
1
3
1
{4: (4, '26', '19'), 5: (5, '13', '6')}
2
13
3