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

带物品

我们设计了一个函数,将值作为输入,并将其与字典中每个项目中存在的值进行比较。如果值匹配,则返回键。

示例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