Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to get a dict key given its value without looping? [duplicate]

so I have a dict with values: [Assuming No Duplicates]

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

and what I want to is do is get they key using the value, so if 1 is given I want it to get they key who has value 1, which is 0 and append it to the list.

 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?

I don't want to make a for loop because I'm trying to do it in linear time.

like image 971
IS92 Avatar asked Feb 03 '26 08:02

IS92


1 Answers

If it's guaranteed that your values are unique, you can create a reversed version of your dict where keys and values are switched:

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])

Output:

{1: 0, 2: 1, -1: -2, 0: -1, -2: -3}
0
like image 62
MrGeek Avatar answered Feb 05 '26 22:02

MrGeek