Reputation: 105
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
Upvotes: 1
Views: 4005
Reputation: 26315
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
Upvotes: 3
Reputation: 36662
You could use filter
:
len(list(filter(lambda x: int(x[1]) > 90, d.items())))
Upvotes: 1
Reputation: 21275
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.
Upvotes: 0
Reputation: 59184
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.
Upvotes: 4