從 Python 中的字典中透過值獲取鍵
Python 字典包含鍵值對。在本文中,我們的目標是在知道元素值時獲取鍵的值。理想情況下,從鍵中提取值,但這裡我們進行相反操作。
使用索引和值
我們使用字典集合的 index 和 values 函式來實現這一點。我們設計了一個列表,先從列表中獲取值,然後從列表中獲取鍵。
示例
dictA = {"Mon": 3, "Tue": 11, "Wed": 8}
# list of keys and values
keys = list(dictA.keys())
vals = list(dictA.values())
print(keys[vals.index(11)])
print(keys[vals.index(8)])
# in one-line
print(list(dictA.keys())[list(dictA.values()).index(3)])輸出
執行上述程式碼,得到以下結果 −
Tue Wed Mon
使用 items
我們設計了一個函式,以值作為輸入,並將其與字典中每個項中的值進行比較。如果值匹配,則返回鍵。
示例
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))輸出
執行上述程式碼,得到以下結果 −
Tue Mon key doesn't exist
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP