Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Python – Lấy giá trị lớn nhất cho mỗi key trong List of Dictionaries

Giới thiệu

Cho một list chứa các dictionary, cần gom lại thành một dictionary chứa giá trị lớn nhất (max) cho mỗi key xuất hiện.

Ví dụ minh họa

my_list = [{"Hi": 18, "there": 13, "Will": 89},
           {"Hi": 53, "there": 190, "Will": 87}]

print("Danh sách dictionary:")
print(my_list)

my_result = {}
for elem in my_list:
    for key, val in elem.items():
        if key in my_result:
            my_result[key] = max(my_result[key], val)
        else:
            my_result[key] = val

print("Dictionary max per key:")
print(my_result)

Kết quả đầu ra

Danh sách dictionary:
[{'Will': 89, 'there': 13, 'Hi': 18}, {'Will': 87, 'there': 190, 'Hi': 53}]
Dictionary max per key:
{'Will': 89, 'there': 190, 'Hi': 53}

Giải thích

  • Duyệt từng dict trong list.
  • Với mỗi cặp key-val, nếu key đã có trong result, cập nhật max; ngược lại gán val.
  • Kết quả chứa max của từng key qua tất cả dict.