好吧,所以現在的問題是我只是無法正確加載文件,因爲它應該...當我得到它實際加載它總是隻保留一個值,而不是所有的價值。正確地使這個文件加載正確嗎?(python 2.7)
lista = {'Cop': '911', 'Police chief': '911'
, 'firemen' : '912', 'fire chef' : '912'
,}
保存功能我想它的工作的罰款(得到了我的問題的代碼)
def save(lista):
spara = lista
from collections import defaultdict
d = defaultdict(list)
fil = open("test" + ".txt","w")
for a, b in lista.items():
d[b].append(a)
for a, b in d.items():
fil.write(a+';'+';'.join(b)+"\n")
fil.close()
像下面的負載功能只是想填補了字典'正常',並已全部鍵和值保存到文件之前。
def load(lista):
ladda = open("test" + ".txt","r")
for namesandnumbers in ladda:
(key,val) = namesandnumbers.split(";")
lista[(val)] = key[:len(key)]
lista = ladda
return lista
while True:
choice = input(" 1 add to list 2 to save 3 to load ")
if choice == 1:
word = raw_input("Type the key: ")
word2 = raw_input("Type the value: ")
lista[word] = word2
print lista
continue
if choice == 2:
save(lista)
elif choice == 3:
load(lista)
elif choice == 4:
False
在它看起來像這樣
911文件;警察;警察局長;
912; firemen; fire chef;
問題是如何加載時分裂。
改用鹹菜。 https://docs.python.org/2/library/pickle.html – FredMan
@FredMan picke不允許使用。如果是的話就會這樣做。 – noname292123
cat(或以其他方式顯示)我們保存的文件內容,並解釋您得到的錯誤或您使用加載函數獲得的輸出。 – FredMan