I'm learning Python and writing a program that keeps track of the total number of vari开发者_Go百科ous types of file extensions. I think a dictionary would be the perfect data type to track this information, something like:
.txt 14
.c 27
.java 12
I have some code written that builds a set, which eliminates duplicate file extensions, but how would I use a dictionary in Python to do the same thing but keep track of the number of occurances?
ext_list = set()
for i in file_list:
ext_list.add(i.extension)
In Python 2.7 or above, you can use collections.Counter
:
from collections import Counter
c = Counter(i.extension for i in file_list)
print(c)
Counter
is a class derived from the standard Python dict
.
If you prefer to use a plain dict
, you can take advantage of its setdefault()
method:
counts = {}
for i in file_list:
counts.setdefault(i.extension, 0)
counts[i.extension] += 1
ext_count = collections.defaultdict(int)
for i in file_list:
ext_count[i.extension] += 1
精彩评论