【问题标题】:Dictionary KeyError when using a string read from serial device使用从串行设备读取的字符串时的字典 KeyError
【发布时间】:2017-11-01 13:51:51
【问题描述】:

我正在读取作为 Python 字典键的串行数据。当我读取串行数据时,它以字节流的形式出现,我将其转换为字符串。当我使用该字符串搜索字典键时,我得到一个 KeyError。

我尝试通过手动输入密钥来搜索相同的密钥,这样可以完美地返回值。我的代码如下,不胜感激!

plates_id = {'TestCylinder100umHard': 8, 'TestCube100umHard': 7, 'MotorMount100umHard': 6, 'InnerShaft100umHard': 5, 'DriveSleeve100umHard': 4, 'DrivePulley100umHard': 3, 'BearingSleeve100umHard': 2, 'Quad': 1, 'Auto Calibration Plate': 0}

s_bytes_new = ser.inWaiting()
s_new = str(ser.read(s_bytes_new))
printing_plate = plates_id[s_new]
print(printing_plate)

这给出了这个错误:

Traceback (most recent call last):
  File "C:/pythonProjects/nanoDLP/touchInterface/printTest.py", line 66, in <module>
  printing_plate = plates_id[s_new]
KeyError: "'Auto Calibration Plate'"

如果您需要更多信息,请告诉我。谢谢,

迪伦

【问题讨论】:

  • 您是否调试打印了repr(s_new) 以查看是否有一些隐藏的空白字符并尝试将其剥离:s_new = s_new.strip()

标签: python dictionary keyerror


【解决方案1】:

使用 .decode() 代替 str,将字节转换为 str

s_new  = ser.read(s_bytes_new).decode()

【讨论】:

  • 哇,这很容易解决!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-30
  • 2023-01-13
  • 1970-01-01
相关资源
最近更新 更多