ภาพรวม
จาก list ของ dictionaries ที่มี key เดียวกัน ให้หาค่า max ของแต่ละ key ทุก dictionary
ตัวอย่างโค้ด
my_list = [
{"Hi": 18, "there": 13, "Will": 89},
{"Hi": 53, "there": 190, "Will": 87}
]
print("The list is:", my_list)
my_result = {}
for d in my_list:
for key, val in d.items():
if key in my_result:
my_result[key] = max(my_result[key], val)
else:
my_result[key] = val
print("The result is:", my_result)
ผลลัพธ์
The list is: [{'Hi': 18, 'there': 13, 'Will': 89}, {'Hi': 53, 'there': 190, 'Will': 87}]
The result is: {'Hi': 53, 'there': 190, 'Will': 89}
วิธีเขียนสั้นกว่า (Pythonic)
from collections import defaultdict
my_result = defaultdict(lambda: float('-inf'))
for d in my_list:
for k, v in d.items():
my_result[k] = max(my_result[k], v)
print(dict(my_result))
Pandas Way (แนะนำสำหรับข้อมูลมาก)
import pandas as pd
df = pd.DataFrame(my_list)
result = df.max().to_dict()
print(result) # {'Hi': 53, 'there': 190, 'Will': 89}
กรณี Key ไม่ครบทุก Dict
my_list = [
{"a": 1, "b": 2},
{"a": 5, "c": 10}
]
# ผลลัพธ์: {'a': 5, 'b': 2, 'c': 10}
# Key ที่ไม่มีในบาง dict จะถูกข้าม (ไม่ error)