2017-04-24 104 views
2

我正在嘗試製作一個保存到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 
可以

別人的幫助我?

+1

哪裏字典獲得創建?它看起來像某處它被重新分配給一個字符串(或者可能初始化爲一個字符串)。在第12行之前嘗試「打印(字典)」,看看它是什麼。 – elethan

+1

它是'{}'不''{}'' –

回答

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 "{}"

+0

整個代碼,(如果你想看到它)在那裏 –

+0

也是文本文件讀取'{}'(新行)'[]'(new行)'{}' –

相關問題