Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
KeyError: 2
#1
Good evening, the second day I struggle with the code, then there is no entry in the database, then the error is KeyError: 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import struct
import sys
import time
import datetime
import pymysql.cursors
from pymodbus.client.sync import ModbusSerialClient
from pymodbus.exceptions import ModbusIOException
from datetime import datetime
 
connection = pymysql.connect(host='127.0.0.1', user='root', password='passwd', db='scales', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)
 
unit = 5
client = ModbusSerialClient(method='rtu', port='/dev/ttyUSB1', parity='N', baudrate=9600, bytesize=8, stopbits=1, timeout=1, strict=False)
 
 
#---------------------------Продукт 1-------------------------
  
while True:
    reply = client.write_registers(52, 1, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result1 = request.registers
    print(result1)
 
    reply = client.write_registers(52, 2, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result2 = request.registers
    print(result2)
 
    reply = client.write_registers(52, 3, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result3= request.registers
    print(result3)
     
    reply = client.write_registers(52, 1, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result4 = request.registers
    print(result4)
 
    reply = client.write_registers(52, 2, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result5 = request.registers
    print(result5)
 
    reply = client.write_registers(52, 3, unit=unit)
    reply = client.write_registers(53, 1, unit=unit)
    reply = client.write_registers(5, 2020, unit=unit) #2020 - Total managment
    request = client.read_holding_registers(51, 1, unit=unit)
    result6= request.registers
    print(result6)
    if (result1 == result4 and result2 == result5 and result3 == result6):
         
        written_as = result1[0] * 0.1, result2[0] * 0.1, result3[0] * 0.1
        print(result1, result2, result3)
         
#---------Write DB--------------------
        with connection:
  
            cur = connection.cursor()
            cur.execute("SELECT * FROM wl5 ORDER BY id DESC LIMIT 1")
  
            rows = cur.fetchall()
  
            for row in rows:
 
             
                print("{0}".format(row[2]))
                print("{0}".format(row[3]))
                print("{0}".format(row[4]))
             
                try:
                    a1 =  float(result1[0] * 0.1)
                    b1 =  float(row[2])
                    silos14 = b1 - a1 - bool(b1 > a1) * 6553.5
                    print ("Расход:"f'{silos14:.1f}')
 
                    a2 =  float(result2[0] * 0.1)
                    b2 =  float(row[3])
                    silos15 = b2 - a2 - bool(b2 > a2) * 6553.5
                    print ("Расход:"f'{silos15:.1f}')
 
                    a3 =  float(result3[0] * 0.1)
                    b3 =  float(row[4])
                    silos16 = b3 - a3 - bool(b3 > a3) * 6553.5
                    print ("Расход:"f'{silos16:.1f}')
 
                except:
#---------write db result-----
                    with connection.cursor() as cursor:
        # Create a new record
                        sql = "INSERT INTO `line5` (`date`, `silos14`, silos15, silos16) VALUES (%s, %s, %s, %s)"
                        today = datetime.datetime.today()
                        newHireDate = today.strftime("%Y-%m-%d-%H.%M")
                        cursor.execute(sql, (newHireDate, silos14, silos15, silos16))
 
 
#------Write db wl5-------
                        sql = "INSERT INTO `wl5` (`date`, `product1`, `product2`, `product3`) VALUES (%s, %s, %s, %s)"
                        today = datetime.datetime.today()
                        newHireDate = today.strftime("%Y-%m-%d-%H.%M")
                        cursor.execute(sql, (newHireDate, result1[0] * 0.1, result2[0] * 0.1,result3[0] * 0.1))
 
                connection.commit()
 
     
        break
Quote:Traceback (most recent call last):
File "/home/pokip/test.py", line 76, in <module>
print("{0}".format(row[2]))
KeyError: 2
Reply
#2
Your error message says that "row" is a dictionary and 2 is not a key in the dictionary. I would print "rows" to see what was returned.

To get where your program throws a key error means that you must have something in the database.
Reply
#3
Apparently "row" does not contain what you expect. So in such cases always add a print statement just before the line where the error occurs.
1
print(row)
What does it show?


Furtheron it is good practice to mention the columns you want instead of "select * from ...". Now you choose all columns and only use row[2], row[3] and row[4]. I is better to specify the columns by name so you can be sure you can use row[0], row[1] and row[2]
Reply
#4
(Aug-16-2022, 05:17 PM)ibreeden Wrote: Apparently "row" does not contain what you expect. So in such cases always add a print statement just before the line where the error occurs.
1
print(row)
What does it show?


Furtheron it is good practice to mention the columns you want instead of "select * from ...". Now you choose all columns and only use row[2], row[3] and row[4]. I is better to specify the columns by name so you can be sure you can use row[0], row[1] and row[2]

Quote:{'id': 1, ‘date’: ‘22.05.2022’, ‘product1’: Decimal('0.0'), ‘product2’: Decimal('3.0'), ‘product3’: Decimal('0.0')}
Traceback (most recent call last):
File “/home/pokip/test.py”, line 77, in <module>
print(“{0}”.format(row))
KeyError: 3
Reply
#5
According to your print row is a dictioany, not a list. You can use row["id"] or row["date"] or row["product1"]. You cannot do row[2] or row[3]. Maybe that should be row["product2"] and row["product3].

Why do you do this "print("{0}".format(row[2]))" when it does the exact same thing as "print(row[2])"?
Reply
#6
(Aug-16-2022, 05:48 PM)deanhystad Wrote: According to your print row is a dictioany, not a list. You can use row["id"] or row["date"] or row["product1"]. You cannot do row[2] or row[3]. Maybe that should be row["product2"] and row["product3].

Why do you do this "print("{0}".format(row[2]))" when it does the exact same thing as "print(row[2])"?

1
2
3
4
Traceback (most recent call last):
  File "/home/pokip/test.py", line 76, in <module>
    print(row[2])
KeyError: 2
Reply
#7
Thanks, figured it out. You need to use row["product1"]. But the problem remained in another :-( everything works as it should, only the result is not written to the database for some reason :-(

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
[15877]
[2178]
[15877]
[34338]
[2178]
[15877]
[34338]
[2178]
[15877]
[34338]
[2178]
[15877]
[34338] [2178] [15877]
0.0
3.0
0.0
load1:-3433.8
load2:-214.8
load3:-1587.7
Reply
#8
That would be because you never execute an code that tries to add items to the database. This only gets called if an exception is raised.
1
2
3
4
5
6
7
8
9
10
11
12
13
                    with connection.cursor() as cursor:
        # Create a new record
                        sql = "INSERT INTO `line5` (`date`, `silos14`, silos15, silos16) VALUES (%s, %s, %s, %s)"
                        today = datetime.datetime.today()
                        newHireDate = today.strftime("%Y-%m-%d-%H.%M")
                        cursor.execute(sql, (newHireDate, silos14, silos15, silos16))
  
  
#------Write db wl5-------
                        sql = "INSERT INTO `wl5` (`date`, `product1`, `product2`, `product3`) VALUES (%s, %s, %s, %s)"
                        today = datetime.datetime.today()
                        newHireDate = today.strftime("%Y-%m-%d-%H.%M")
                        cursor.execute(sql, (newHireDate, result1[0] * 0.1, result2[0] * 0.1,result3[0] * 0.1))
Get rid of the try/except and see what happens.
Reply
#9
oops. Thank you. Everything is working :-)
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020