์ผ๋ฐ์ ์ธ ๋ฐฉ๋ฒ
keyList = ["a", "a", "a", "b", "b", "c"]
dic_2 = dict()
for key in keyList:
if key not in dic_2:
dic_2[key] = 0
dic_2[key] += 1
print(dic_2) # {'a': 3, 'b': 2, 'c': 1}
Python
๋ณต์ฌ
get(key[, default]) ์ฌ์ฉ
๋ถ๊ธฐ์ฒ๋ฆฌ๊ฐ ํ์์์ด์ ์ ์ฉํ๋ค.
keyList = ["a", "a", "a", "b", "b", "c"]
dic_3 = dict()
for key in keyList:
dic_3[key] = dic_3.get(key, 0) + 1 # ๊ธฐ์กด์ key ์์ผ๋ฉด ํด๋น value ๋ฐ์์ค๊ณ , ์์ผ๋ฉด 0
print(dic_3) # {'a': 3, 'b': 2, 'c': 1}
Python
๋ณต์ฌ
defaultdict(type) ์ฌ์ฉ
from collections import defaultdict
keyList = ["a", "a", "a", "b", "b", "c"]
dic_3 = defaultdict(int) # key ๊ฐ ์กด์ฌํ์ง ์์๋ ํด๋น ํ์
์ ์ด๊ธฐ๊ฐ์ผ๋ก ์ธํ
ํด์ค
for key in keyList:
dic_3[key] = dic_3[key] + 1
print(dic_3) # {'a': 3, 'b': 2, 'c': 1}
Python
๋ณต์ฌ
defaultdict ์ ์ธ์๋ก int(0) ๋ฟ๋ง ์๋๋ผ list([]), set(()) ๋ฑ ๋ค์ํ ํ์
์ด ๋ค์ด์ฌ ์ ์์
fromkeys(list, value) ์ฌ์ฉ
key๋ง ๋ฐ์์ค๊ณ , value๋ฅผ ์น ๋ค 0์ผ๋ก ๋ง๋ค๊ณ ์ถ์ ๋ ์ธ๋งํ ๊ฒ ๊ฐ์๋ฐ, ๋ฑํ ์ ์ฉํ์ง๋ ์์๋ฏ
keyList = ["a", "a", "a", "b", "b", "c"]
dic_1 = dict.fromkeys(keyList, 0)
print(dic_1) # {'a': 0, 'b': 0, 'c': 0}
Python
๋ณต์ฌ
๊ณ ์ ๋ value ๋ก๋ง ์ด๊ธฐํ๊ฐ ๊ฐ๋ฅํ๋ค๋ณด๋๊น ์ข ๋ณ๋ก๊ธดํ๋ค.
collections.Counter ์ฌ์ฉ
from collections import Counter
dic_3 = Counter("hello world")
print(dic_3) # Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
print(dict(dic_3)) # {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
dic_4 = Counter(keyList)
print(dict(dic_4)) # {'a': 3, 'b': 2, 'c': 1}
Python
๋ณต์ฌ