0
0

辞書内の値に応じて値を集計【Python】

Posted at

説明

  1. sum() 関数を使って、data リスト内の各辞書から type に基づいて time の値を取得し、それらを合計します。
data = [
    {"time":  60, "type": "1"},
    {"time":  80, "type": "1"},
    {"time": 120, "type": "2"},
    {"time": 180, "type": "2"},
]

total_time = sum(
    entry["time"] if entry["type"] == "1" else 0
    for entry in data
)

print(total_time) # 140
0
0
1

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