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

Lấy Key Từ Value Trong Dictionary (Get Key from Value in Dictionary) trong Python


Dictionary Python chứa các cặp key-value. Trong bài này ta nhằm lấy giá trị của key khi ta biết giá trị của phần tử. Lý tưởng là value được trích xuất từ key nhưng ở đây ta làm ngược lại.

Với index và values

Ta sử dụng hàm index và values của dictionary để đạt được điều này. Ta thiết kế một danh sách để trước lấy values sau đó lấy keys từ nó.

Ví dụ

dictA = {"Mon": 3, "Tue": 11, "Wed": 8} # danh sách keys và values keys = list(dictA.keys()) vals = list(dictA.values()) print(keys[vals.index(11)]) print(keys[vals.index(8)]) # một dòng print(list(dictA.keys())[list(dictA.values()).index(3)])

Đầu ra

Chạy mã trên cho kết quả sau:

Tue Wed Mon

Với items

Ta thiết kế một hàm nhận value làm đầu vào và so sánh với value hiện diện trong mỗi item của dictionary. Nếu value khớp, key được trả về.

Ví dụ

dictA = {"Mon": 3, "Tue": 11, "Wed": 8} def GetKey(val):     for key, value in dictA.items():       if val == value:           return key       return "key doesn't exist" print(GetKey(11)) print(GetKey(3)) print(GetKey(10))

Đầu ra

Chạy mã trên cho kết quả sau:

Tue Mon key doesn't exist