เมื่อจำเป็นต้องค้นหาคีย์ที่เกี่ยวข้องกับค่าเฉพาะในพจนานุกรม คุณสามารถใช้วิธี "ดัชนี" ได้
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ตัวอย่าง
my_dict ={"Hi":100, "there":121, "Mark":189}
print("The dictionary is :")
print(my_dict)
dict_key = list(my_dict.keys())
print("The keys in the dictionary are :")
print(dict_key)
dict_val = list(my_dict.values())
print("The values in the dictionary are :")
print(dict_val)
my_position = dict_val.index(100)
print("The value at position 100 is : ")
print(dict_key[my_position])
my_position = dict_val.index(189)
print("The value at position 189 is")
print(dict_key[my_position]) ผลลัพธ์
The dictionary is :
{'Hi': 100, 'there': 121, 'Mark': 189}
The keys in the dictionary are :
['Hi', 'there', 'Mark']
The values in the dictionary are :
[100, 121, 189]
The value at position 100 is :
Hi
The value at position 189 is
Mark คำอธิบาย
-
มีการกำหนดพจนานุกรมและแสดงบนคอนโซล
-
คีย์ของพจนานุกรมสามารถเข้าถึงได้โดยใช้ '.keys' และจะถูกแปลงเป็นรายการ
-
สิ่งนี้ถูกกำหนดให้กับตัวแปร
-
ค่าของพจนานุกรมสามารถเข้าถึงได้โดยใช้ '.values' และจะถูกแปลงเป็นรายการ
-
สิ่งนี้ถูกกำหนดให้กับตัวแปรอื่น
-
มีการเข้าถึงดัชนีค่าและกำหนดให้กับตัวแปร
-
นี้จะแสดงเป็นผลลัพธ์