Python:如何在不循环的情况下获得给定值的字典键?

标签 python dictionary

<分区>

所以我有一个带有值的字典:[假设没有重复项]

mydict={0: 1, 1: 2, -2: -1, -1: 0, -3: -2}

我想要做的是使用值获取它们的键,因此如果给出 1,我希望它获取值为 1 的键,即 0,并将其附加到列表中。

 finalO=[]
  if x in myddict.values():
      finalO.append([mydict.**getKeyByVal**(x)])--> so is there's a built in function that will allow me to do that?

我不想做一个 for 循环,因为我想在线性时间内完成它。

最佳答案

如果可以保证您的值是唯一的,您可以创建一个反转版本的 dict,其中键和值被切换:

mydict = {0: 1, 1: 2, -2: -1, -1: 0, -3: -2}

my_inverted_dict = dict(map(reversed, mydict.items()))

print(my_inverted_dict)
print(my_inverted_dict[1])

输出:

{1: 0, 2: 1, -1: -2, 0: -1, -2: -3}
0

关于Python:如何在不循环的情况下获得给定值的字典键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123757/

相关文章:

python - 在 Python 中为线性拟合(具有两个参数)生成置信区间等高线图

单独文件中的python字典

python - 检查字典中是否存在特定的键和值

python - 如何使用默认 key :value pairs given in another dict 更新 python 字典

python - 理解 d[key] = None 的用法

python - 我应该使用哪种布局在 python 中的 igraph 中获得非重叠边缘?

python - Django REST 框架 : 'WSGIRequest' object has no attribute 'query_params'

python - 如何删除未连接到二进制图像中循环的白色像素

python - 将 pandas 虚拟添加到 numpy 数组中?

vba - 在 VBA 宏中使用字典的简单 VLOOKUP