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?

【Python初心者】辞書形式でCSVを扱う(DictReader / DictWriter)

Posted at

CSVファイルを扱うとき、カラム名(ヘッダー)をキーとして使いたい場面がありました。
そのような場合に、Pythonの csv モジュールにある DictReaderDictWriter を使うと便利だったので、使い方を記録しておきます。

辞書形式でCSVを読み込む(csv.DictReader)

まず、次のようなCSVファイルを用意します。

# sample.csv の内容
name,age,city
Alice,30,New York
Bob,25,Los Angeles

このCSVファイルを DictReader を使って読み込んでみます。

import csv

with open("sample.csv", newline="", encoding="utf-8") as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row)
{'name': 'Alice', 'age': '30', 'city': 'New York'}
{'name': 'Bob', 'age': '25', 'city': 'Los Angeles'}

ポイント

  • ヘッダー行(1行目)が自動的に辞書のキーとして使われます。
  • 各行は dict 型として取得されます。
  • 値はすべて文字列として読み込まれるため、必要に応じて型変換が必要です。

辞書形式でCSVに書き込む(csv.DictWriter)

次に、辞書形式のデータをCSVファイルに書き込む方法を試します。

import csv

data = [
    {"name": "Alice", "age": 30, "city": "New York"},
    {"name": "Bob", "age": 25, "city": "Los Angeles"}
]

with open("output.csv", "w", newline="", encoding="utf-8") as f:
    fieldnames = ["name", "age", "city"]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    writer.writerows(data)
# 出力される output.csv の内容
name,age,city
Alice,30,New York
Bob,25,Los Angeles

ポイント

  • fieldnames で書き込み対象のキーとその順序を指定します。
  • writeheader() を呼ぶと、ヘッダー行が自動的に書き込まれます。
  • writerows() に辞書のリストを渡すことで、複数行を一括で出力できます。

通常の reader / writer との違い

比較項目 reader / writer DictReader / DictWriter
各行の形式 リスト 辞書(dict)
キー情報 なし(インデックス) ヘッダー行を使う
可読性 やや低い 高い(カラム名でアクセス可能)

DictReader / DictWriter は、特にデータのカラム名を意識して処理したい場面で役に立つと感じました。

まとめ

  • DictReader はCSVを辞書形式で読み込むときに使います。
  • DictWriter は辞書データをCSVファイルに書き出すときに使います。
  • カラム名でデータにアクセスしたい場合にはとても便利です。
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?