TypeError: string indices must be integers, not str in Pt[]

TypeError: string indices must be integers, not str in Pt[]

为什么会出现这个错误?

File Parser.py", line 214, in writeData
comments = subItem['Comments']
TypeError: string indices must be integers, not str

短堆栈跟踪:

213:             for subItem in Pt['C']:
214:                comments = subItem['Comments']

代码:

Pt[] is defined as is a list.
Pt = self.createPatient()

def createPatient(self):
    Pt = {
        'S' : {},
        'C' : []
    }
    return Pt

And 'C' is:

#

这里是 'C'(格式)定义的更大样本。 格式是列表字典。看看这个有用吗?

Formats = {
...
    ['For Future Use', 11, ''],
],
'C' : [
    ['use', 1, ''],
    ['Call', 15, ''],
    ['Leg', 1, '1'],
    ['Rank', 1, 'A'],
    ['DateTime Entered', 14, ''],
    ['User ID', 11, ''],
    ['Comments', 255, ''],
    ['Narrative ID', 11, ''],
    ['For Future Use', 11, ''],
],
'R' : [
    ['Use', 1, ''],
    ['Call #', 15, ''],
    ['Leg', 1, '1'],
....
}

您似乎在代码的前面某处将 subItem 定义为字符串,而不是字典。检查你对

的定义
subItem = ....

我猜它是一个字符串。

C的子元素仍然是列表,需要通过索引访问。 做你想做的,最好的方法是用字典替换 'C' 中的列表。

所以改用下面的

{
  'DateTime Entered' : [ 14, ''],
  'User ID' : [11, ''],
  'Comments' : [ 255, '']
}

顶部的两行代码将起作用。