พจนานุกรม Python มีคู่ค่าคีย์ ในบทความนี้เราจะมาดูวิธีรับคีย์ขององค์ประกอบที่มีค่าสูงสุดในพจนานุกรม Python ที่กำหนด
ด้วยค่าสูงสุดและรับ
เราใช้ฟังก์ชัน get และฟังก์ชัน max เพื่อรับคีย์
ตัวอย่าง
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA, key=dictA.get)
print("The Key with max value:\n",MaxKey) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue ด้วย itemgetter และ max
ด้วยฟังก์ชัน itemgetter เรารับรายการของพจนานุกรมและโดยการสร้างดัชนีไปยังตำแหน่งที่หนึ่ง เราจะได้รับค่า ต่อไปเราจะใช้ว่าทำไมฟังก์ชัน max และสุดท้ายเราก็ได้คีย์ที่จำเป็น
ตัวอย่าง
import operator
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
print("Given Dictionary:\n",dictA)
# Using max and get
MaxKey = max(dictA.items(), key = operator.itemgetter(1))[0]
print("The Key with max value:\n",MaxKey) ผลลัพธ์
การเรียกใช้โค้ดข้างต้นทำให้เราได้ผลลัพธ์ดังต่อไปนี้ -
Given Dictionary:
{'Mon': 3, 'Tue': 11, 'Wed': 8}
The Key with max value:
Tue