In these situations EAFP style is suitable:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try
and except
statements. The technique contrasts with the LBYL style common to many other languages such as C.
In Python code it could look like:
>>> content_ratings = {}
>>> ratings = ['4+', '4+', '4+', '9+', '9+', '12+', '17+']
>>> for rating in ratings:
... try:
... content_ratings[rating] += 1
... except KeyError:
... content_ratings[rating] = 1
...
>>> content_ratings
{'4+': 3, '9+': 2, '12+': 1, '17+': 1}
For counting there is built-in Counter in built-in collections module which has some useful methods as well:
>>> from collections import Counter
>>> ratings = ['4+', '4+', '4+', '9+', '9+', '12+', '17+']
>>> content_ratings = Counter(ratings)
>>> content_ratings
Counter({'4+': 3, '9+': 2, '12+': 1, '17+': 1})
>>> content_ratings['4+']
3
>>> content_ratings.most_common()
[('4+', 3), ('9+', 2), ('12+', 1), ('17+', 1)]
>>> content_ratings.most_common(1)
[('4+', 3)]