【问题标题】:Python 3, Turning csv file into a dictionaryPython 3,将 csv 文件转换为字典
【发布时间】:2017-09-13 11:27:29
【问题描述】:

文件类似于:

6, 'bird', 'flies', False

它需要像这样订购:

{'bird': (6,'flies', False)}

这是我目前所拥有的,但格式不正确。

{"'bird'": '1'}

我当前的代码:

def read_info_file(filename):

    d = {}
    count = 0

    file = open(filename, "r")
    lines = file.readlines()

    for line in lines:
        split = tuple(line.split(","))

        if count > 0:
            d[split[1]] = split[0]
        count += 1

    return d

我也不能在这个问题中导入任何模块。

【问题讨论】:

  • 另外,向我们展示您所说的“格式不正确”是什么意思。
  • 另外,您可能会发现使用内置的csv module 会更容易

标签: python python-3.x file csv io


【解决方案1】:

下面会根据您的格式要求格式化 csv。

代码:

导入 csv

从 pprint 导入 pprint

定义过滤器(str):

str = str.strip().strip("'")
return str

def read_info_file(文件路径):

try:

    res = {}

    csvfile = open(filepath,'r')
    csv_reader = csv.reader(csvfile)

    for row in csv_reader:
        res[filter(row[1])] = (int(row[0]),filter(row[2]),bool(row[3]))

except Exception as e:
    print("Exception occurred: " + str(e))
finally:
    csvfile.close()
return res

res = read_info_file('file.csv') pprint(res)

输出:

{'动物': (7, '苍蝇', True), '鸟': (6, '苍蝇', True), '昆虫': (8, '苍蝇', True)}

【讨论】:

  • 您撤消了我的编辑并破坏了您的答案格式。
  • 很遗憾我无法为这个问题导入任何内容
【解决方案2】:

使用 Python 手动解析 csv 文件通常比其价值更多。这是解析单个行的一种简单方法,使用生成器,同时仍使用 csv 模块:

代码:

import csv

def parse_my_csv(csv_file):
    for line in csv_file.readlines():
        # replacing comma/space with comma
        yield line.replace(", ", ",")

with open('myfile.csv', 'rU') as csvfile:
    csv_read = csv.reader(parse_my_csv(csvfile), quotechar="'")
    for row in csv_read:
        d = {row[1]: (int(row[0]), row[2], bool(row[3]))}
        print(d)

结果:

{'bird': (6, 'flies', True)}

【讨论】:

    【解决方案3】:

    要在没有任何导入模块的情况下执行此操作,您可以使用如下推导:

    代码:

    def read_info_file(filename):
        with open(filename, 'rU') as f:
            return {row[1]: (int(row[0]), row[2], bool(row[3]))
                    for row in [
                        [c.strip().strip("'") for c in line.split(',')]
                        for line in f.readlines()
                    ]}
    

    测试:

    print(read_info_file('myfile.csv'))
    

    结果:

    {'bird': (6, 'flies', True)}
    

    【讨论】:

      猜你喜欢
      • 2018-08-13
      • 2021-12-22
      • 2021-04-01
      • 1970-01-01
      • 2023-03-20
      • 2017-03-27
      • 2018-12-09
      • 2021-07-31
      • 1970-01-01
      相关资源
      最近更新 更多