Một dictionary Python chứa các cặp key-value. Trong bài này ta sẽ xem cách lấy key của phần tử có giá trị lớn nhất trong dictionary cho trước.
Với max và get
Ta sử dụng hàm get và hàm max để lấy key.
Ví dụ
dictA = {"Mon": 3, "Tue": 11, "Wed": 8} print("Given Dictionary:\n",dictA) # Sử dụng max và get MaxKey = max(dictA, key=dictA.get) print("The Key with max value:\n",MaxKey)Đầu ra
Chạy mã trên cho kết quả sau:
Given Dictionary: {'Mon': 3, 'Tue': 11, 'Wed': 8} The Key with max value: TueVới itemgetter và max
Với hàm itemgetter ta lấy các item của dictionary và lấy chỉ số 1 để lấy giá trị. Tiếp theo áp dụng hàm max và cuối cùng lấy key cần thiết.
Ví dụ
import operator dictA = {"Mon": 3, "Tue": 11, "Wed": 8} print("Given Dictionary:\n",dictA) # Sử dụng max và get MaxKey = max(dictA.items(), key=operator.itemgetter(1))[0] print("The Key with max value:\n",MaxKey)Đầu ra
Chạy mã trên cho kết quả sau:
Given Dictionary: {'Mon': 3, 'Tue': 11, 'Wed': 8} The Key with max value: Tue