How would you go about using a value to display the key. Lets say it goes like this: dict = {'number1':[1,2,3,4,5], 'number2':[6,7,8,9,10]} Using one of the values, how would I be able to print the key?
CodePudding user response:
Assuming that there is such a key, you can use generator comprehension:
dct = {'number1':[1,2,3,4,5], 'number2':[6,7,8,9,10]}
x = 9
output = next((k for k, v in dct.items() if x in v))
print(output) # number2
If you are going to do this procedure a lot of times repeatedly, then it might be better to once make a dictionary that maps a number to its corresponding key, and then use it repeatedly.
dct_inverse = {x: k for k, lst in dct.items() for x in lst}
print(dct_inverse[x]) # number2
CodePudding user response:
You can do this:
key_lst = list(my_dict.keys())
val_lst = list(my_dict.values())
position = val_lst.index("some value")
print(key_lst[position])