Home > Back-end >  Comparing if an element in a dictionary is greater than a variable
Comparing if an element in a dictionary is greater than a variable

Time:02-14

I am new to Python and have just recently learnt what dictionaries are and was experimenting with some code.

import random
random_number= random.randint(0,100)
print(random_number)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3','Grade 2': 19,'Grade 1': 9,}

def if_random_number(score):
    if random_number > scores[]:
        print('\nYou are grade {}'.format(score, scores.get(item, 'invalid')))

I am trying to make it compare if the random_number is greater than the elements in the list scores it, will print out your grade.
Since I'm new to coding and honestly suck I need some help

CodePudding user response:

Here's a rework of your code that I think does what you're looking for:

import random
random_number= random.randint(0,100)

scores = {89: 'Grade 9', 79: 'Grade 8', 69: 'Grade 7', 59: 'Grade 6', 49: 'Grade 5', 39: 'Grade 4', 29: 'Grade 3', 19: 'Grade 2',  9: 'Grade 1'}

def if_random_number(random_score):
    for score, grade in scores.items():
        if random_score >= score:
            print('\nYour score of {} is grade {}'.format(score, grade))
            break
    else:
        print('\nYou suck')

if_random_number(random_number)

Sample results:

Your score of 9 is grade Grade 1

Your score of 79 is grade Grade 8

You iterate over your 'scores' dictionary looking for the first entry where the key (the score) is less than the random number you computed. The else clause is a more advanced trick where you can do something if in a for loop, your test never succeeded and so you never called break to break out of the loop. Since your random number can be less than all keys in scores (can be < 9), you need this else clause to be sure that you always print something.

CodePudding user response:

In Python you can iterate over dicts this way:

for key, value in dictionary.items():
    # Here you have the keys as key and values as value

In your case:

for score in scores.keys():
    if (score >= random_number):
        print(scores[score])

or otherwise

for score, mark in scores.items():
    if (score >= random_number):
        print(mark)

You can also do it with list comprehension:

[print(value) for key, value in scores.items() if key >= random_number]
  • Related