Python 中 dictionary 中的值關聯的鍵
當需要找出 dictionary 中特定值關聯的鍵時,可以使用“index”方法。
以下是對此的演示 −
示例
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說明
定義了一個 dictionary,並在控制檯上顯示。
可以使用“keys”訪問 dictionary 的鍵並轉換為列表。
這分配給一個變數
可以使用“values”訪問 dictionary 的值並轉換為列表。
這分配給另一個變數。
訪問值的索引並分配給一個變數。
這將作為輸出顯示。
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP