Python:对多个dicts TypeError:“str”对象不支持项赋值

2024-05-15 05:37:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

sample_fh = dir + "sampleManifest.txt"
kids = {}
fid = {}
parents = {}
status = {}
sex = {}
with open(sample_fh) as f:
    for line in f:
            line = line.rstrip('\n')
            row = line.split('\t')
            fid = row[0]
            iid = row[1]
            relation  = row[5]
            status = row[6]
            sex = row[7]
            if relation != "Mother" and relation != "Father":
                    kids[iid] = 1
                    status[iid] = status
                    fid[iid] = fid
                    sex[iid]= row[7]
            if relation == "Mother" or relation == "Father":
                    parents[(fid,relation)]  = iid

我得到这个错误:

^{pr2}$

不知道发生了什么事。以前的论坛说这个错误是由于你改变了字符串,但我很确定我没有改变任何字符串。在


Tags: sampleifstatus错误linekidsrowrelation
2条回答

在代码status = row[6]中重新分配status,这样它就不再是dict了,要么为dict使用另一个名称,要么更改循环中的状态,只是不要同时使用它。在

status = {} # starts as a dict
status = row[6] # now the name status points to something else i.e a str
fid = row[0]
iid = row[1]
relation = row[5]
status = row[6]
sex = row[7]

在这里,使用从文件中的行解析的简单值覆盖字典。就这样,这本字典就不见了。例如,status现在是一个字符串,因此当您稍后执行status[iid]操作时,您将使用索引访问从字符串中获取单个字符。在

您应该重命名那里的变量,这样就不会覆盖字典:

^{pr2}$

相关问题 更多 >

    热门问题