python函数Namerror:未定义名称'dictionary'

问题描述

我想加载文件并将其转换为字典。然后,想使用加载的文件显示数据。用户选择的输入介于1和2之间,以便确定要运行的功能。 问题是如果我在1之前按2,则它将显示消息“字典为空”。同样,当我加载文件并尝试运行显示数据时,它显示“ Nameerror:未定义名称'dictionary'” 代码如下:(提前感谢)

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()

解决方法

首先。您提供的代码有很多错误。 关键是您应该使用变量 my_dict 来存储您加载的字典,如果类型2位于1之前,则显示空字典。

尝试下面的代码列表:

import csv


def load_data():
    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():
    my_dict = {}
    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()
,

您尚未在my_dict中定义任何line 24,因此它给出了name error。 您应该添加以下行:

my_dict = {}

如果想要所需的输出。

,

在选择2中,您没有数据,也没有给my_dict分配任何值,然后调用display_data,您应该将这些数据加载到my_dict中并将其传递给函数 这是代码

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:
          my_dict = load_data()
          display_data(my_dict)
main()