【问题标题】:CSV reader inserts brackets in textCSV 阅读器在文本中插入括号
【发布时间】:2019-08-26 09:29:32
【问题描述】:

我正在尝试使用 python 的 csv 模块读取 CSV 文件(即简单表)并创建一个字典,其中第一列是键,第二列是值。我的问题是,当我解析每一行/每一行时,第二列的文本会用括号格式化。

例如,假设管道分隔表格的每一列:

城市 |编号

休斯顿 | 1

奥斯汀 | 2

达拉斯 | 3

(抱歉,格式不佳,但我无法弄清楚如何让 Stack Overflow 正确格式化表格,即使在尝试之后也是如此。)

我的代码是:

my_dict = defaultdict(list)
with open(my_file, newline='') as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)  # Skip the row containing the column headers
    for row in csv_reader:
        region_name, region_code = row[0], int(row[1])
        my_dict[region_name].append(region_code)

当我打印my_dict 时,我看到“Houston”的值是 [1],而不是 1。我还看到“Austin”的值是 [2],而不是 2。所有其他的也是如此价值观。

更准确地说,如果我输入:

print(my_dict["Houston"])

我得到的值是 [1] 而不是 1

我知道csv 模块将每一行/每一行转换为一个列表,但我不知道为什么第二列添加了括号。为什么会发生这种情况,我怎样才能摆脱括号?

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    为什么会这样

    因为你告诉 python 使用一个列表作为默认值,即defaultdict(list),然后你在该列表上调用.append(region_code)

    我怎样才能去掉括号?

    my_dict = {}
    with open(my_file, newline='') as csv_file:
        csv_reader = csv.reader(csv_file)
        next(csv_reader)  # Skip the row containing the column headers
        for row in csv_reader:
            region_name, region_code = row[0], int(row[1])
            my_dict[region_name] = region_code
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多