Dol*_*ids 1 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]
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
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
status[iid] = status
TypeError: 'str' object does not support item assignment
Run Code Online (Sandbox Code Playgroud)
不知道发生了什么事.以前的论坛说这个错误是在你改变字符串时引起的,但我很确定我没有改变任何字符串.
你重新分配status
你的代码,status = row[6]
因此它不再是一个字典,要么为你的字典使用另一个名字,要么在你的循环中改变状态,不要两者都使用它.
status = {} # starts as a dict
status = row[6] # now the name status points to something else i.e a str
Run Code Online (Sandbox Code Playgroud)
fid = row[0]
iid = row[1]
relation = row[5]
status = row[6]
sex = row[7]
Run Code Online (Sandbox Code Playgroud)
在这里,您将使用从文件中的行解析的简单值覆盖字典.因此,字典完全消失了.例如,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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
372 次 |
最近记录: |