python函数名称错误:未定义名称“dictionary”

2024-05-05 15:39:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我想加载一个文件并将其转换为字典。然后,希望使用加载的文件来显示数据。选择的用户输入介于1和2之间,以决定运行哪个函数。 问题是,如果我在1之前按2,它将显示消息“dictionary is empty”。同样,当我加载文件并尝试运行显示数据时,它显示“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()

Tags: 文件csv数据datadictionaryismydef
3条回答

在选项2中,在调用display_data之前,您没有数据或没有为my_dict分配任何值。您应该将这些数据加载到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()

首先,你提供的代码有很多错误。 关键点是,如果在1之前键入2,则应使用变量my_dict存储加载的dict或显示空dict

请尝试下面的代码列表:

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

您没有在line 24中定义任何my_dict,这就是它给出name error的原因。 您应添加以下行:

my_dict = {}

如果你想要你想要的输出

相关问题 更多 >