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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With