0
1

More than 3 years have passed since last update.

collections.defaultdict

Posted at
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}})
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1