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} """
- d = dict() to create an empty dictionary.
- The result of d.get(k, 0) is the corresponding value if k (key) is in the dictionary, or 0 if there is no. By setting +1 to d.get(k, 0), the number of occurrences of the key is counted.
- Built-in — Python 3.9.4 documentation (get function)
- Source:cpython/dictobject.c at main · python/cpython · GitHub(Line 2867)
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.
- (*1): Since there are two for statements in the dictionary compremation and thecount function, the calculation amount is O(n^2).
Source:cpython/listobject.c at main · python/cpython · GitHub(Line 2560)
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)
コメント