import collections
d = {}
l = ['a', 'a', 'a', 'b', 'b', 'c']
for word in l:
if word not in d:
d[word] = 0
d[word] += 1
print(d)
d = {}
for word in l:
d.setdefault(word, 0)
d[word] += 1
print(d)
d = collections.defaultdict(int)
for word in l:
d[word] += 1
print(d)
d = collections.defaultdict(set)
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
for k, v in s:
d[k].add(v)
print(d)
実行結果;
{'a': 3, 'b': 2, 'c': 1}
{'a': 3, 'b': 2, 'c': 1}
defaultdict(<class 'int'>, {'a': 3, 'b': 2, 'c': 1})
red 1
blue 2
red 3
blue 4
red 1
blue 4
defaultdict(<class 'set'>, {'red': {1, 3}, 'blue': {2, 4}})