1
s = 'aeqwtwegwa'
d = {}
for c in s:
if c not in d:
d[c] = 0
d[c] += 1
print(d)
Execution result of 1
{'a': 2, 'e': 2, 'q': 1, 'w': 3, 't': 1, 'g': 1}
2
s = 'aefqwdqfqwe'
d = {}
for c in s:
d.setdefault(c, 0)
d[c] += 1
print(d)
Execution result of 2
{'a': 1, 'e': 2, 'f': 2, 'q': 3, 'w': 2, 'd': 1}
If you read and write the defaultdict from the standard library,
3
from collections import defaultdict
s = 'raegiowejgohg'
d = defaultdict(int)
for c in s:
d[c] += 1
print(d)
print(d['g'])
Execution result of 3
defaultdict(<class 'int'>, {'r': 1, 'a': 1, 'e': 2, 'g': 3, 'i': 1, 'o': 2, 'w': 1, 'j': 1, 'h': 1})
3
Recommended Posts