3

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.

IS92
  • 690
  • 1
  • 13
  • 28

3 Answers3

7

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
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
2

You will have to loop for this, since you have to invert the mapping of the dictionary. In order to do so you can use a dictionary comprehension:

d = {j:i for i,j in mydict.items()}
print(d[1])
# 0
yatu
  • 86,083
  • 12
  • 84
  • 139
2
mydict={0: 1, 1: 2, -2: -1, -1: 0, -3: -2}

search_value = 1

# List comprehension to return items if they match a search value
# This populates a list automatically
final0 = [k for k, v in mydict.items() if v == search_value]

# Note: If you have a value that is paired with more than one key
# then you might want to use set() and iterate through that to ensure
# your values aren't duplicates.

mydict2 = {0: 1, 1: 2, -2: -1, -1: 0, -3: -2, 4: 1} # Added matching value at end
final0 = [i for i in set([k for k, v in mydict.items() if v == search_value])]
Mark Moretto
  • 2,344
  • 2
  • 15
  • 21
  • You might want to add some comments along with the code to make it clearer for OP – yatu Sep 26 '19 at 19:59
  • @yatu Good idea. Updated! I didn't really bring anything new to the table, but using a dictionary might not be the best choice for OP. We'd need more context to figure that out. – Mark Moretto Sep 26 '19 at 20:59