get a count of dictionary keys with values greater than some integer in python
dictionary, integer, python
Solution
You could use `collections.Counter` and a "classification function" to get the result in one-pass:
def classify(val):
res = []
if val > 1:
res.append('> 1')
if val > 20:
res.append('> 20')
if val > 50:
res.append('> 50')
return res
from collections import Counter
countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2}
Counter(classification for val in countDict.values() for classification in classify(val))
# Counter({'> 1': 5, '> 20': 2, '> 50': 1})
Of course you can alter the return values or thresholds in case you want a different result.
But you were actually pretty close, you probably just mixed up the syntax - correct would be:
a = sum(1 for i in countDict.values() if i >= 2)
because you want to iterate over the `values()` and check the condition for each value.
What you got was an exception because the comparison between
>>> countDict.values()
dict_values([2, 409, 2, 41, 2])
and an integer like `2` doesn't make any sense.
Problem
I have a dictionary. The keys are words the value is the number of times those words occur. ``` countDict = {'house': 2, 'who': 41, 'joey': 409, 'boy': 2, 'girl':2} ``` I'd like to find out how many elements occur with a value of more than 1, with a value of more than 20 and with a value of more than 50. I found this code ``` a = sum(1 for i in countDict if countDict.values() >= 2) ``` but I get an error that I'm guessing means that values in dictionaries can't be processed as integers. ``` builtin.TypeError: unorderable types: dict_values() >= int() ``` I tried modifying the above code to make the dictionary value be an integer but that did not work either. ``` a = sum(1 for i in countDict if int(countDict.values()) >= 2) builtins.TypeError: int() argument must be a string or a number, not 'dict_values' ``` Any suggestions?