Python 根据字典的Value获取对应的Key

Python的字典是非常好用的,但是如何在已知Value的情况获得对应的Key呢?

  • 一个字典的Key是不一样的
  • 一个字典的Vaulev是可能重复的

根据Python官方的描述:

If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

在迭代的过程中,没有对字典进行修改,那么Key和Value总是保持对应关系。

列表解析式

1
2
3
4
a = {'John': 60, 'Alice': 95, 'Paul': 80, 'James': 75, 'Bob': 85}

name = [key for key, value in a.items() if value == 75]
print(name) # 输出结果:['James']

利用 keys() 、values()、index() 函数

1
2
3
4
a = {'John': 60, 'Alice': 95, 'Paul': 80, 'James': 75, 'Bob': 85}

name = list(a.keys())[list(a.values()).index(75)]
print(name) # 输出结果:James

将原字典进行反转得新字典(此方法仅限于Value没有重复值)

1
2
a_inv = {value: key for key, value in a.items()}
print(a_inv[75]) # 输出结果:James

Comments

Your browser is out-of-date!

Update your browser to view this website correctly.&npsb;Update my browser now

×