简体   繁体   English

如何从字典中的键获取值

[英]how to get values from the keys in dictionary

I have some code for car registration for parking. 我有一些停车注册的代码。 I have created a dictionary with car registration number as keys and rest information as values. 我创建了一个字典,其中汽车注册号作为键,休息信息作为值。 I am trying to get details (values) of each registration by entering the registration number. 我想通过输入注册号来获取每个注册的详细信息(值)。 Even if the id is in the dictionary it's showing message not found in the dictionary. 即使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" 

The error message I am getting is: 我得到的错误消息是:

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

But the dictionary has the above registration number: 但字典上面有注册号:

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

I think your problem is that your function def createNameDict(filename): doesn't return anything, so the data_dict inside it is just a local variable! 我认为你的问题是你的函数def createNameDict(filename):不返回任何东西,所以里面的data_dict只是一个局部变量!

Make the last line of the function return data_dict and then use it like data_dict = createNameDict(filename) . 使函数的最后一行return data_dict ,然后像data_dict = createNameDict(filename)一样使用它。 There is no need for the global variable part, so just remove that. 不需要全局变量部分,所以只需删除它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM