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

Tìm key tương ứng với value trong dictionary Python

Chuyển keys và values thành list, dùng list.index() để tìm vị trí value, sau đó lấy key tại vị trí đó.

Ví dụ

my_dict = {"Hi": 100, "there": 121, "Mark": 189}
print("Dictionary:", my_dict)

keys = list(my_dict.keys())
values = list(my_dict.values())
print("Keys:", keys)
print("Values:", values)

pos = values.index(100)
print("Key của value 100:", keys[pos])

pos = values.index(189)
print("Key của value 189:", keys[pos])

Kết quả

Dictionary: {'Hi': 100, 'there': 121, 'Mark': 189}
Keys: ['Hi', 'there', 'Mark']
Values: [100, 121, 189]
Key của value 100: Hi
Key của value 189: Mark

Giải thích

  • my_dict.keys() và my_dict.values() trả về view, chuyển thành list để dùng index.
  • values.index(100) trả về chỉ số đầu tiên có giá trị 100.
  • Lấy key tại chỉ số đó từ list keys.
  • Lưu ý: Nếu value trùng lặp, chỉ tìm thấy key đầu tiên. Cách tốt hơn: dùng dictionary comprehension ngược hoặc vòng lặp.