dimanche 27 septembre 2020

python function Namerror: name 'dictionary' is not defined

I would like to load a file and convert it to a dictionary. then, would like to use the loaded file to display the data. user input for choice is between 1 and 2, in order to decide which function to run. The catch is if I press 2 before 1 then it will display the message "dictionary is empty". Again, when I load the file and try to run display data, it is showing "Nameerror: name 'dictionary' is not defined" The code is as below: (Thanks in advance)

def load_data():
  import csv
  open_data = open('file.csv', 'r')
  datasets = csv.reader(open_data)
  mydict = {row[0]:row[1:] for row in datasets}
  return mydict

def display_data(my_dict):
  ds = my_dict
  if ds == {}:
    print("dictionary is empty")
  else:
    for key, value in ds.items():
      print(key)
      print(value)
       
def main():
    while True:
    choice = int(input("select 1 or 2"))    
    if choice == 1:
      my_dict = load_data()
      print(my_dict)    
    elif choice == 2:
      display_data(my_dict)
main()

Aucun commentaire:

Enregistrer un commentaire