【问题标题】:Converting Data to a Dictionary From a CSV Without The First Row在没有第一行的情况下将数据从 CSV 转换为字典
【发布时间】:2020-07-25 12:15:38
【问题描述】:

假设我有一个如下所示的 CSV 文件:

Title,Category,Price,Rating
To Kill a Mockingbird,Fiction,11.99,89
Killing Lincoln,Nonfiction,15.99,85

我想把它转换成如下所示的字典:

{'To Kill a Mockingbird': ('Fiction', 11.99, 89), 'Killing Lincoln': ('Nonfiction', 15.99, 85), ... }

我想确保删除列的标题(即不包括第一行)。

我首先尝试了以下方法。

import csv
reader = csv.reader(open('bookdata.csv'))
result = {}

for row in reader:
    key = reader[0]
    result[key] = reader[1:]
print(result)

但是当我这样做时,我没有成功删除第一行,并且字典包含列表,而不是元组。我怎样才能解决这个问题?我还想确保 \n 字符被剥离。

【问题讨论】:

  • 是不同列的csv还是同一列中的全部用逗号分隔?

标签: python python-3.x csv dictionary tuples


【解决方案1】:

你很接近。首先,有一个错误,你说reader 而应该是row。那么它只是一个使用next 跳过标题行并将列表转换为元组的问题。

import csv
from decimal import Decimal

reader = csv.reader(open('bookdata.csv'))
# skip header
next(reader)
result = {}

for row in reader:
    # only needed if empty lines in input
    if not row:
        continue
    key = row[0]
    # Book with category, price in decimal, and other thingie??
    result[key] = row[1], Decimal(row[2]), int(row[3])

print(result)

【讨论】:

  • 在这个过程中是否可以将数值转换为整数和浮点数?
  • @324 - 已更新。我使用Decimal 而不是float,因为它看起来像美元价格,而二进制浮点数只是十进制数的估计值。如果您愿意,可以将其更改为浮动,但可能会损失一些准确性。
  • 我试过这个@tdelaney,但还是不行:( ``` books = {'To Kill a Mockingbird': ('Fiction', '11.99', '89'), 'Killing Lincoln': ('Nonfiction', '15.99', '85')} from decimal import Decimal for row in books: # 仅当输入为空行时才需要 if not row: continue key = row[0] # Book with category,十进制价格和其他东西?? books[key] = row[1], Decimal(row[2]), int(row[3]) print(books) ```
  • 我试着用 float 代替,但也没有用。
猜你喜欢
  • 1970-01-01
  • 2012-11-21
  • 2015-02-22
  • 2017-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多