Python. csv到可用的字典

n3schb8v  于 2022-12-06  发布在  Python
关注(0)|答案(2)|浏览(140)

我试图建立一个字典形式的csv文件,然后给予另一个函数这个字典,但Python形式的某种对象,我不能处理我的知识。输出的打印是:在0x00000172BBB1CCD0处的字典阅读器对象

def load_cities():
"""
Read CSV-Data from File into a Dictonary.
"""
    city_dict = {}
       
    with open(CURRENT_DIR / FILE, mode = "r", encoding = "utf-8") as fin:
        city_dict = csv.DictReader(fin)
        print(type(city_dict), city_dict)

    sort_by_name(city_dict)
2hh7jdfx

2hh7jdfx1#

DictReader创建一个对象,该对象的操作类似于常规读取器,但它将每行中的信息Map到一个字典,该字典的键由可选的fieldnames参数给定。
您的数据是什么样子的?如果您想获得一个字典列表(对于每一行),您可以执行以下操作:

print(list(city_dict))

如果要创建一个词典,可以按如下方式创建

print({row[0]:row[1] for row in csv.reader(fin)})
s2j5cfk0

s2j5cfk02#

我已经从另一个问题修改了一个解决方案,这是有效的。但是dictReader能建立可用的词典吗?

def load_cities():
"""
Read CSV-Data from File into a Dictonary.
"""
    results = []

    file = open("worldcities_short.csv", mode="r", encoding="utf-8")
    cities_string = file.read()
    file.close()

    input_list = cities_string.split("\n") 
    for row in input_list:
        words = row.split(",")
        results.append(words)
    header = results.pop(0)
    city_dict = {}
    for row in results:
        first_name = row[0]
        city_dict[first_name] = dict(zip(header, row))
    print(city_dict)

相关问题