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

标签 python python-3.x dictionary data-structures

我想获取给定值的字典键列表。例如

my_dict = {1: 2, 3: 3, 4: 2}
value = 2

我想得到1和4。

如何获取对应的key列表?

最佳答案

使用列表理解,您可以按值和键过滤:

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

或者使用 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)

关于python - 如何从python中的字典中检索具有给定值的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43897904/

相关文章:

python - 如何设置PYTHONPATH和项目布局

list - Python - 在理解中比较两个列表

python - Python函数的Dask Apply

python 2.7 : remove a key from a dictionary by part of key

python - 检查字典列表中是否已经存在值?

python - Python中的增量最近邻算法

python - 是否可以可移植确定 Python 中 off_t 的适当映射以用于 ctypes?

python - TensorFlow freeze_graph.py : The name 'save/Const:0' refers to a Tensor which does not exist

python - 获取上传的音频/视频文件的持续时间

c++映射范围内的删除