Home > database >  How do I get a dict key from an int when the dict values are lists?
How do I get a dict key from an int when the dict values are lists?

Time:11-17

I have the python dict:

my_dict = {'C': [1,2,3,4,5,6,7,8,9,10,11,12,15,18,46,64,67,73,78,83],
            'B': [13,14,22,32,38,39,42,59,68,74,79,84],
            'A': [16,17,19,23,31,37,40,50,51,60,70,75,80,85],
            'S': [20,25,33,36,43,44,48,49,57,61,62,63,71,76,81,86,88,89,92,94],
            'SS': [21,24,26,47,52,53,54,56,66,69,72,77,82,87,91,93],
            'SS ': [27,28,29,30,34,35,41,45,55,58,65,90,95,96,97,98],
            'SSS': [99,100]}

How would I get the key 'C' as the output when I give it the integer value 78 as the input for the code:

var_playerXp = 0

my_dict_key = int(input("Give an integer between 1 and 100: "))
if my_dict_key.lower() == 'c':
   var_playerXp  = 5
elif my_dict_key.lower() == 'b':
   var_playerXp  = 10
elif my_dict_key.lower() == 'a':
   var_playerXp  = 25

etc. through 'SSS'.

I tried to check for the same way as a dictionary with integer values:

my_dict_key = list(my_dict.keys())[list(my_dict.values()).index(my_dict_key)]

However, I only got the error: ValueError: 78 is not in list

CodePudding user response:

my_dict_key = 78
out = [k for k, v in my_dict.items() if my_dict_key in v]
print(*out)
C
  • Related