Count the number of occurrences of each key in the python dictionary!

Describes how to count the number of occurrences of each key in a dictionary (dictionary).
The key is each element of the list.

Use for statement

The processing time is shorter than the method of using the dictionary compremation and thecount function described below. This method is recommended because the processing time is shorter compared to the method described below, and the number of types does not change much.

l = ["beer", "on", "bear", "in", "beer"]
d = dict()
for k in l:
    d [k] = d.get(k, 0) + 1
print(d)
""" output
{'beer': 2, 'on': 1, 'bear': 1, 'in': 1}
"""

I referred to the following.
python – Using a dictionary to count the items in a list – Stack Overflow(mmmdreg)

Use dictionary compremation and count function

It is better to have fewer lines than the method using the for statement described above, but the calculation amount is large (*1). If processing time is important, this method is not recommended.

l = ["beer", "on", "bear", "in", "beer"]
d = {k:l.count(k) for k in l}
print(d)
""" output
{'beer': 2, 'on': 1, 'bear': 1, 'in': 1}
"""

I referred to the following.
python – Using a dictionary to count the items in a list – Stack Overflow(Ashish Kumar Verma)

コメント

タイトルとURLをコピーしました