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

IS9*_*S92 2 python dictionary

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

mydict={0: 1, 1: 2, -2: -1, -1: 0, -3: -2}
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用该值获取它们的键,因此如果给出 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?
Run Code Online (Sandbox Code Playgroud)

我不想做一个 for 循环,因为我试图在线性时间内做到这一点。

MrG*_*eek 5

如果可以保证您的值是唯一的,则可以创建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])
Run Code Online (Sandbox Code Playgroud)

输出:

{1: 0, 2: 1, -1: -2, 0: -1, -2: -3}
0
Run Code Online (Sandbox Code Playgroud)