0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python3 CSVをタプルやリストに読み込む

Last updated at Posted at 2022-02-13

CSVをタプルやリストに読み込む

CSVをタプルやリストに読み込むにはcsv.DictReaderクラスを作成してtuple()list()に渡します。空のリストとforは不要です。

tuple(csv.DictReader(...)) # タプルへ変換
list(csv.DictReader(...))  # リストへ変換

文字列から作成したCSVをタプルへ変換する具体例は次の通りです。

CSV文字列➞タプル変換
import csv
from pprint import pp

csv_raw  = "A, B, C\n1,2,3\n4,5,6\n7,8,9".split("\n")
csv_rows = tuple(csv.DictReader(csv_raw))

pp(csv_rows)
#({'A': '1', ' B': '2', ' C': '3'},
# {'A': '4', ' B': '5', ' C': '6'},
# {'A': '7', ' B': '8', ' C': '9'})

上の出力結果が'A': '1'であるように値は文字列として読み込まれます。JSONなどに変換する場合は読み込み後に数値へ変換してください。

csv.DictReaderクラスがtuple()list()にそのまま渡せる理由

csv.DictReaderクラスがtuple()list()にそのまま渡せるのは__iter__()メソッドを実装するためです。そのため、csv.DictReaderクラスは内包表記、filter()map()も適用できます。

import csv
from pprint import pp

csv_raw    = "A, B, C\n1,2,3\n4,5,6\n7,8,9".split("\n")
csv_reader = csv.DictReader(csv_raw)
pp(tuple(d for d in csv_reader if int(d["A"]) % 2 == 0))
# ({'A': '4', ' B': '5', ' C': '6'},)

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?