Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Get Key with Maximum Value ใน Dictionary Python: หาคีย์ที่มีค่าสูงสุด

ได้ Dictionary ต้องการคีย์ที่มีค่า (value) สูงสุด

วิธี 1: ใช้ max() กับ dict.get

dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
max_key = max(dictA, key=dictA.get)
print(max_key)  # Tue

วิธี 2: ใช้ operator.itemgetter กับ max()

import operator
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
max_key = max(dictA.items(), key=operator.itemgetter(1))[0]
print(max_key)  # Tue

สรุป

ทั้งสองวิธีให้ผลลัพธ์เหมือนกัน วิธี 1 เรียบง่ายกว่า วิธี 2 ใช้ฟังก์ชันมาตรฐาน operator.itemgetter ซึ่งอาจเร็วกว่าเล็กน้อย