我正在嘗試製作一個保存到python文件的電話簿。這裏是代碼有問題的片段:字典錯誤:「TypeError:'str'對象不支持項目分配」
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
可以
別人的幫助我?
哪裏字典獲得創建?它看起來像某處它被重新分配給一個字符串(或者可能初始化爲一個字符串)。在第12行之前嘗試「打印(字典)」,看看它是什麼。 – elethan
它是'{}'不''{}'' –