Python:对多个dicts使用相同的键TypeError:';str';对象不支持项分配

Python:对多个dicts使用相同的键TypeError:';str';对象不支持项分配,python,dictionary,types,Python,Dictionary,Types,这是我的密码 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]

这是我的密码

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
我得到这个错误:

status[iid] = status
TypeError: 'str' object does not support item assignment

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

您在代码中重新分配
状态
状态=行[6]
,因此它不再是一个dict,或者为dict使用另一个名称,或者在循环中更改状态,只是不要同时为这两个名称使用它

status = {} # starts as a dict
status = row[6] # now the name status points to something else i.e a str

在代码中重新分配
status
,使其不再是dict,或者为dict使用另一个名称,或者更改循环中的状态,只是不要同时使用它

status = {} # starts as a dict
status = row[6] # now the name status points to something else i.e a str
在这里,您将使用从文件中的行解析的简单值覆盖字典。因此,这本字典完全不存在了。例如,
status
现在是一个字符串,因此当您稍后执行
status[iid]
时,您将使用索引访问从字符串中获取单个字符

您应该在此处重命名变量,以免覆盖词典:

for line in f:
    line = line.rstrip('\n')
    row = line.split('\t')
    row_fid = row[0]
    iid = row[1]
    relation  = row[5]
    row_status = row[6]
    row_sex = row[7]
    if relation != "Mother" and relation != "Father":
            kids[iid] = 1
            status[iid] = row_status
            fid[iid] = row_fid
            sex[iid]= row_sex
    if relation == "Mother" or relation == "Father":
            parents[(row_fid, row_relation)]  = iid
在这里,您将使用从文件中的行解析的简单值覆盖字典。因此,这本字典完全不存在了。例如,
status
现在是一个字符串,因此当您稍后执行
status[iid]
时,您将使用索引访问从字符串中获取单个字符

您应该在此处重命名变量,以免覆盖词典:

for line in f:
    line = line.rstrip('\n')
    row = line.split('\t')
    row_fid = row[0]
    iid = row[1]
    relation  = row[5]
    row_status = row[6]
    row_sex = row[7]
    if relation != "Mother" and relation != "Father":
            kids[iid] = 1
            status[iid] = row_status
            fid[iid] = row_fid
            sex[iid]= row_sex
    if relation == "Mother" or relation == "Father":
            parents[(row_fid, row_relation)]  = iid

状态是str不是dictout状态是str不是dictoohh谢谢。这是一个Perl程序员的坏习惯。我习惯于在脚本中声明%status和$status,以便知道使用哪个值。我现在觉得自己好笨。谢谢哦,谢谢你。这是一个Perl程序员的坏习惯。我习惯于在脚本中声明%status和$status,以便知道使用哪个值。我现在觉得自己好笨。谢谢谢谢,这是Perl的一个坏习惯。我将使用%status和$status作为散列和值谢谢,这是Perl的一个坏习惯。我将使用%status和$status作为散列和值