简体   繁体   中英

Counting values in a dictionary that are greater than a certain number in Python?

I'm looking to create a function that prints a count of the number of times a grade is found to be greater than or equal to 90.

So if the dictionary is:

d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}

The output should be 2

I get the following error when trying to run my code: ValueError: invalid literal for int() with base 10: 'Tom'

def overNum():
    d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'}
    count = 0


    for number in d:
        if int(number) in d and int(number) >= 90 in d:
            count += 1

            print(count)

if the user inputs: numTimes() the output should be:

2

for number in d: will iterate through the keys of the dictionary, not values. You can use

for number in d.values():

or

for name, number in d.items():

if you also need the names.

You can collect the items in a list that are greater or equal to 90 then take the len() :

>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> len([v for v in d.values() if int(v) >= 90])
2

Or using sum() to sum booleans without building a new list, as suggested by @Primusa in the comments:

>>> d = {'Luke':'93', 'Hannah':'83', 'Jack':'94'}
>>> sum(int(i) >= 90 for i in d.values())
2

You need to iterate over the key-value pairs in the dict with items()

def overNum():
    d = {'Tom':'93', 'Hannah':'83', 'Jack':'94'}
    count = 0

    for name, number in d.items():
        if int(number) >= 90:
            count += 1
    print(count)

Also there are some issues with the if statement that i fixed.

您可以使用filter

len(list(filter(lambda x: int(x[1]) > 90, d.items())))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM