[英]appending dictionary to master list
由于某种原因,这不允许我在字典的键中添加字符串项。
这是我的代码:
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
我猜你的意思是
userDict["zip"] = singleUserList[4]
代替
singleUserList["zip"] = singleUserList[4] # <-- singleUserList is a list,
# and you cannot index it via a string
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.