Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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’.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading