Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将csv导入为字典-无类型错误_Python_Dictionary - Fatal编程技术网

Python 将csv导入为字典-无类型错误

Python 将csv导入为字典-无类型错误,python,dictionary,Python,Dictionary,如何将.csv文件导入为字典 我正在尝试将.csv文件作为字典导入。csv文件有两列:一个名为“AIRPORT CODE”的键和一个名为“AIRPORT”的元素。我首先尝试将其作为列表导入,因为我认为从列表转换为字典更容易 def load_airports_dict(filename): import csv reader = csv.reader(open(filename, 'r')) data_list = [] for row in reader:

如何将.csv文件导入为字典

我正在尝试将.csv文件作为字典导入。csv文件有两列:一个名为“AIRPORT CODE”的键和一个名为“AIRPORT”的元素。我首先尝试将其作为列表导入,因为我认为从列表转换为字典更容易

def load_airports_dict(filename):
    import csv

    reader = csv.reader(open(filename, 'r'))
    data_list = []

    for row in reader:
        data_list.append(row)

    d = { }

    for row in data_list:
        d[row[0]] = row[1]
    print(d)
不幸的是,当试图调用一个函数对字典进行切片时,我得到了“NoneType”对象是不可下标的,即使我在函数之外运行代码,它也会给出我想要的东西

  • 不要导入定义中的内容

  • 您需要一个
    return
    语句

  • 尽管如此:

    import csv
    def load_airports_dict(filename):
        result = {}
        with open(filename, 'r') as handle:
            reader = csv.reader(handle)
            for row in reader:
                result[row[0]] = row[1]
        return result
    

    请显示完整的回溯。您的函数没有
    return
    语句。如果我看到过,那就太难了。