我正在尝试制作一个在python中保存到文件的电话簿。以下是带有问题的代码片段:
import os
f = open("save")
forbidden = f.readline()
forbiddens = f.readline()
dictionary = f.readline()
stop = 0
global arguments
print("phonebook os by me")
def write():
global forbidden
global forbiddens
global dictionary
f = open("save")
f.write(forbidden and '\n' and forbiddens and '\n' and dictionary)
f.close()
def add_cc():
global forbidden
global dictionary
global arguments
name = arguments[1]
number = int(arguments[2])
if name in forbidden:
print("403: forbidden!")
elif name in dictionary:
print("406: Not acceptable! This item is already in the dictionary!")
else:
dictionary[name] = number
write()
start()
def del_cc():
global arguments
global dictionary
name = arguments[1]
del dictionary[name]
write()
start()
def get_cc():
global arguments
global forbidden
global dictionary
name = arguments[1]
if name in dictionary:
print(dictionary[name])
elif name in forbidden:
print("403: Forbidden!")
else:
print("404: Item not Found.")
start()
(休息时间太长)
问题出现在dictionary[name] = number
第12行。我得到的错误是
dictionary[name] = number
TypeError: 'str' object does not support item assignment
有人可以帮助我吗?
答案 0 :(得分:0)
是的,我可以帮助你:)。
检入代码以分配给dictionary
。变量dictionary
不是字典,而是字符串,因此代码中的某处将是:
dictionary = " evaluates to string "
或等同于它。
以上您已经从错误消息中了解到,但似乎没有帮助您知道如何避免错误。所以这里你必须改变你的代码,以便错误消失:
import os
f = open("save")
forbidden = f.readline()
forbiddens = f.readline()
dictionary = {} # now it is a dictionary not a string "{}"