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'}
4

1 回答 1

2

我认为你的问题是你的函数def createNameDict(filename):没有返回任何东西,所以data_dict它内部只是一个局部变量!

制作函数的最后一行,return data_dict然后像data_dict = createNameDict(filename). 不需要全局变量部分,所以只需删除它。

于 2012-05-13T14:03:46.693 回答