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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

说明

  • 定义了一个 dictionary,并在控制台上显示。

  • 可以使用“keys”访问 dictionary 的键并转换为列表。

  • 这分配给一个变量

  • 可以使用“values”访问 dictionary 的值并转换为列表。

  • 这分配给另一个变量。

  • 访问值的索引并分配给一个变量。

  • 这将作为输出显示。

更新于:17-4-2021

363 次浏览

开端您的职业生涯

完成课程即可获得认证

开始
广告