///
Search

dict/defaultdict/Counter ๋กœ ๊ฐœ์ˆ˜์„ธ๊ธฐ

๋ถ„๋ฅ˜
๋”•์…”๋„ˆ๋ฆฌ
์ž๋ฃŒ๊ตฌ์กฐ
์†์„ฑ
์ƒ์„ฑ์ผ
2022/01/22 14:40
์ตœ์ข… ์ˆ˜์ •
2023/04/03 15:32

์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•

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
๋ณต์‚ฌ