如何从python中的字典中检索具有给定值的所有键

ani*_*ani 2 python dictionary data-structures python-3.x

我想得到给定值的字典键列表.例如

my_dict = {1: 2, 3: 3, 4: 2}
value = 2
Run Code Online (Sandbox Code Playgroud)

我想获得1和4.

如何获取通讯键列表?

Dhi*_*aTN 7

使用列表推导,您可以按值和按键过滤:

given_value = 2
keys_list = [k for k, v in my_dict.items() if v == given_value]  # [1, 4]
Run Code Online (Sandbox Code Playgroud)

或者使用Python内置filter:

given_value = 2
keys_iter = filter(lambda k: my_dict[k] == given_value, my_dict.keys()) # return an iterator
keys_list = list(keys_iter)
Run Code Online (Sandbox Code Playgroud)