【Python基礎】辞書のループ処理|keys, values, itemsの使い方

辞書とforの組み合わせ

辞書とforループを組み合わせると、全てのキーと値をまとめて処理できます。

1. items()でキーと値を同時に取得

scores = {"数学": 85, "英語": 92, "理科": 78}

for subject, score in scores.items():
    print(f"{subject}:{score}点")
▶ 出力結果

数学:85点
英語:92点
理科:78点

2. 辞書のリストを処理する(実用例)

users = [
    {"name": "田中", "score": 85},
    {"name": "鈴木", "score": 92},
    {"name": "佐藤", "score": 78},
]

for user in users:
    print(f"{user['name']}:{user['score']}点")
▶ 出力結果

田中:85点
鈴木:92点
佐藤:78点

3. 辞書を集計に使う(カウント)

votes = ["田中", "鈴木", "田中", "佐藤", "田中", "鈴木"]
count = {}

for name in votes:
    count[name] = count.get(name, 0) + 1

print(count)
▶ 出力結果

{'田中': 3, '鈴木': 2, '佐藤': 1}
< 前の記事便利なメソッド(get, keys, items)
次の記事 >12. 関数の定義と利用

コメントする

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

上部へスクロール