出于某种原因,它不允许我将字符串项添加到字典中的键。
这是我的代码:
splitUserList(line)
的例子:
>>> splitUserList("1|24|M|technician|85711 ")
['1', 24, 'M', 'technician', '85711']
代码:
def createUserList():
userList = []
totalUserList = []
f = open("u.user.txt")
for line in f:
userDict = {}
singleUserList = splitUserList(line)
userDict["age"] = singleUserList[1]
userDict["gender"] = singleUserList[2]
userDict["occupation"] = singleUserList[3]
singleUserList["zip"] = singleUserList[4]
userList.append(userDict)
return userList
为什么不起作用?
Traceback (most recent call last):
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 1, in <module>
# Used internally for debug sandbox under external interpreter
File "/Applications/WingIDE.app/Contents/MacOS/src/debug/tserver/_sandbox.py", line 20, in createUserList
TypeError: list indices must be integers, not str
答案 0 :(得分:4)
我猜你的意思
userDict["zip"] = singleUserList[4]
而不是
singleUserList["zip"] = singleUserList[4] # <-- singleUserList is a list,
# and you cannot index it via a string