π μ΄ κΈμ <μ λ¬Έκ°λ₯Ό μν νμ΄μ¬(fluent python) - 루μμλ νλ§λ₯> λ₯Ό λ²μνμ΅λλ€.
νμ΄μ¬μ κ°λ°μκ° μ½κΈ°λ, μ΄ν΄νκΈ°λ μ¬μλ³΄μ¬ μ΄λ μ λ μ΅μν΄μ‘λ€ μΆμ μκ° ν λ¨κ³ λ κΉμ 곡λΆκ° νμν΄μ§λ μΈμ΄λΌκ³ μκ°νλ€. νμ΄μ¬μ΄λΌλ μΈμ΄κ° κ°μ§ λ΄μ¬μ νΌν¬λ¨Όμ€μ νκ³λ λ³κ°λ‘ μΉλλΌλ, νμ΄μ¬μ΄ μ¬λμ μΈμ΄μ λΉμ·νκ² λ§λ€κΈ° μν΄ μ ν¬μ₯ν΄ λμ κ·Έ μμ μ‘°κΈ λ λ€μ¬λ€ λ³Ό νμκ° μκΈ°λ μκ°μ λ§μ£Όνκ² λλ€. μ‘°κΈ λ μ μ°½ν νμ΄μ¬ μΈμ΄ μ¬μ©μκ° λκΈ° μν μ§μλ€μ νλμ© μνμμΌλ³΄λ©°, μ΄μ μ 무μ¬μ½ μμ±νκ±°λ μ°Έκ³ νλ μ½λλ€μ κΉμ μμ€μμ λ€μ μ΄ν΄ν μ μκ² λλ€.
- Pythonμ΄λΌλ μΈμ΄λ₯Ό ꡬμ±νλ ν΅μ¬ μμμΈ 'dict' νμ μ λν μ΄ν΄λλ₯Ό λμΈλ€
- 'dict' νμ μ λμ μ±λ₯μ 보μ₯νλ 'Hash table'μ μμλ³Έλ€
- 'Hash table'μ κΈ°λ°μ λ λ€λ₯Έ νμ μΈ 'set'μ μ΄ν΄νλ€
dict
νμ
μ νλ‘κ·Έλ¨μμ λ리 μ¬μ©λ λΏλ§ μλλΌ, νμ΄μ¬ ꡬνμ ν΅μ¬ μμμ΄λ€. λͺ¨λ λ€μμ€νμ΄μ€(Module namespaces), ν΄λμ€μ μΈμ€ν΄μ€ μμ±, ν¨μ ν€μλ μΈμ(Function keyword arguments)λ dictionariesκ° μ μ©λ νμ΄μ¬μ ν΅μ¬ κ΅¬μ‘°λ€ μ€ μΌλΆλ€.
dict
λ ν΅μ¬μ μΈ μν μ νκΈ° λλ¬Έμ λμ μμ€μΌλ‘ μ΅μ ν λμ΄μλ€. νμ΄μ¬μ dict
κ° λμ μ±λ₯μ κ°μ§λ μ΄μ λ Hash tables
μ κΈ°λ°μ λκΈ° λλ¬Έμ΄λ€.
μ΄λ² μ±ν°μμ dict
μ λ§μ°¬κ°μ§λ‘ hash tables
λ‘ κ΅¬νλ set
νμ
λ λ€λ£¬λ€. dictionaries
μ sets
λ₯Ό ꡬνν λ, Hash tables
μ λμ λ°©μμ μλ κ²μ΄ μ€μνλ€.
collections.abc
λͺ¨λμ dict
λ μ μ¬ν νμ
μ μΈν°νμ΄μ€λ₯Ό ννννλ ABCμΈ Mapping
κ³Ό MutableMapping
μ μ 곡νλ€.
νμ€ λΌμ΄λΈλ¬λ¦¬μ λͺ¨λ mapping typesμ κΈ°λ³Έ dictλ₯Ό ꡬνμ μ¬μ©νλ€. λ°λΌμ, ν€(key)κ° hashable
ν΄μΌ νλ€λ νκ³μ μ λμΌνλ€.
What is hashable?
str
, bytes
, numeric types
λ λͺ¨λ hashablefrozenset
λν hashable (frozensetμ μ μμ λ°λΌ μμλ€μ΄ hashable)tuple
λ λͺ¨λ μμ΄ν
μ΄ hashableμΌ κ²½μ°μλ§ hashabletupleμ hashability
tt = (1, 2, (30, 40))
hash(tt) # 8027212646858338501
tl = (1, 2, [30, 40]) # TypeError: unhashable type: 'list'
tf = (1, 2, frozenset([30, 40]))
hash(tf) # -4118419923444501110
μ΄μ κ°μ κΈ°λ³Έ μμΉμ λ°λΌ, dictionariesλ₯Ό μ¬λ¬ κ°μ§ λ°©λ²μΌλ‘ λ§λ€ μ μλ€.
a = dict(one=1, two=2, three=3)
b = {'one': 1, 'two': 2, 'three': 3}
c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) # zip returns iterator of tuples
d = dict([('two', 2), ('one', 1), ('three', 3)])
e = dict({'three': 3, 'one': 1, 'two': 2})
a == b == c == d == e # True
νμ΄μ¬ 2.7λΆν° listcomps
μ genexps
μ΄ dict
comprehensionμ μ μ©λμλ€. dictcomp
λ μμμ iterableλ‘λΆν° key:value
μμ μμ±νμ¬ dict κ°μ²΄λ₯Ό λ§λ λ€.
DIAL_CODES = [ # <1>
(86, 'China'),
(91, 'India'),
(1, 'United States'),
(62, 'Indonesia'),
(55, 'Brazil'),
(92, 'Pakistan'),
(880, 'Bangladesh'),
(234, 'Nigeria'),
(7, 'Russia'),
(81, 'Japan')
]
country_code = {country: code for code, country in DIAL_CODES} # <2>
country_code # {'China': 86, 'India': 91, 'Bangladesh': 880...}
{code: country.upper() for country, code in country_code.items() if code < 66} # {1: 'UNITED STATES', 55: 'BRAZIL', 62: 'INDONESIA', 7: 'RUSSIA'}
<1> μμ κ°μ§ 리μ€νΈλ dict μμ±μμ λ°λ‘ μ¬μ©ν μ μλ€.
<2> μμ μμκ° λ°λμλ€.