2012-05-13 58 views
0

我有一些停車的汽車註冊代碼。我創建了一本汽車註冊號字典作爲鍵和休息信息的字典值。我試圖通過輸入註冊號碼來獲取每個註冊的詳細信息(值)。即使id在字典中,它也會顯示字典中未找到的消息。如何從字典中的鍵獲取值

global variable 
data_dict = {} 
def createNameDict(filename): 
    path = "C:\Users\user\Desktop" 
    basename = "ParkingData_Part2.txt" 
    filename = path + "\\" + basename 
    file = open(filename) 
    contents = file.read() 
    print contents,"\n" 


    data_list = [lines.split(",",1) for lines in contents.split("\n")] 
    #data_list.sort() 
    #print data_list 
    #dict_list = [] 

    for line in data_list: 
    keys = line[0] 
    values = line[1] 

    data_dict[keys] = values 
    print data_dict,"\n" 
    print data_dict.keys(),"\n" 
    print data_dict.values(),"\n" 
    print data_list 
def detailForRegistrationNumber(regNumber): 
    regNumber == "keys" 
    if regNumber in data_dict: 
    print data_dict[regNumber] 
    else: 
    print regNumber, "Not in dictionary" 

我得到的錯誤信息是:

======= Loading Progam ======= 
>>> detailForRegistrationNumber('EDF768') 
EDF768 Not in dictionary 

但詞典有上述註冊號:

{'HUY768': ' Wilbur Matty, 8912, Creche_Parking', 'GH7682': ' Clara Hill, 7689, AgHort_Parking', 'GEF123': ' Jill Black, 3456, Creche_Parking', 'WER546': ' Olga Grey, 9898, Creche_Parking', 'TY5678': ' Jane Miller, 8987, AgHort_Parking', 'ABC234': ' Fred Greenside, 2345, AgHort_Parking', 'KLOI98': ' Martha Miller, 4563, Vet_Parking', **'EDF768'**: ' Bill Meyer, 2456, Vet_Parking', 'JU9807': ' Jacky Blair, 7867, Vet_Parking', 'DF7800': ' Jacko Frizzle, 4532, Creche_Parking', 'ADF645': ' Cloe Freckle, 6789, Vet_Parking'} 
+0

如果你在你的路徑中使用反斜槓(protip:不要,甚至windows支持正斜槓!),你需要轉義它們或者簡單地使用*原始字符串*:'r'C:\ whatever \ path'' – ThiefMaster

+0

你的'主要'方法在哪裏? createNameDict在哪裏被調用?從上面的代碼片斷中,我無法分辨它是否被調用,或者你忘記調用它。如果您忘記調用它,那麼爲任何參數調用detailForRegistrationNumber將會說它不在字典中。 – Neal

+3

您似乎沒有從您的其他帖子關於如何輸入該文本的任何建議:http://stackoverflow.com/questions/10545544/converting-lists-to-dictionaries/10545736#10545736 – hexparrot

回答

2

我覺得你的問題是,你的函數def createNameDict(filename):不返回任何東西,所以它裏面的data_dict只是一個局部變量!

使函數的最後一行return data_dict然後像data_dict = createNameDict(filename)一樣使用它。不需要全局變量部分,只需刪除它即可。

相關問題