从 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

更新于:2020 年 4 月 6 日

3K+ 人浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.