νμ΄μ¬ λμ λ리(Dictionary)μ λͺ¨λ κ²
λμ λ리(Dictionary)
νμ΄μ¬ λμ λ리λ Key, Value νμμΌλ‘ μ΄λ£¨μ΄μ§ ν΄μ μκ³ λ¦¬μ¦ μ»¨ν μ΄λμ λλ€. 리μ€νΈ, ννκ³Όλ λ€λ₯΄κ² λ°μ΄ν°μ μμλ μ€μνμ§ μμ΅λλ€. νΉμ Keyλ₯Ό ν΅ν΄ Valueλ₯Ό κ°μ Έμ€λ μ°κ΄ 컨ν μ΄λλΌλ μ μ λλ€. 리μ€νΈ, ννμ μνμ€ μ»¨ν μ΄λλΌκ³ ν μ μμ΅λλ€.
νμ΄μ¬ λμ λ리λ ν΄μν μ΄λΈ(Hash Table)λ‘ κ΅¬μ±λμ΄ μκΈ° λλ¬Έμ λ°μ΄ν°μ κ²μμ΄ λ§€μ° λΉ λ₯Έ νΈμ λλ€. μ¬κΈ°μ μ€μν νΉμ§μ Keyμ κ³ μ μ±μ λλ€. Keyλ μ€λ³΅μ νμ©νμ§ μμ΅λλ€. λ°λΌμ Keyμ ννμ μ¬μ© κ°λ₯νμ§λ§(immutable), 리μ€νΈλ λΆκ°λ₯ν©λλ€(mutable).
κΈ°λ³Έ
dic = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
dic['name'] # 'seorang' -> value λ°ν
dic['sex'] = 'male' # μμ μΆκ°
del dic['phone'] # μμ μμ
ν¨μ
- Keyλ§ λ½μλ΄κΈ°(keys)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> a.keys()
dict_keys(['name', 'phone', 'birth'] # dict_keys κ°μ²΄ λ°ν
>>>> list(a.keys())
['name', 'phone', 'birth'] # 리μ€νΈλ‘ λ³ν
>>>> for k in a.keys():
print(k)
2. Value 리μ€νΈ λ§λ€κΈ°(values)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> a.values()
dict_values(['seoarang', '1313414', '0819'] # dict_values κ°μ²΄ λ°ν
3. Key, Value μ μ»κΈ°(items)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> a.items()
dict_items([('name', 'seoarang'), ('phone', '1313414'), ('birth', '0819')]) # dict_items κ°μ²΄ λ°ν
>>>> for key, val in a.items():
print(f"key : {key}, value : {value}")
4. Keyλ‘ Value μ»κΈ°(get)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> a.get('name')
'seoarang'
>>>> a.get('age')
None
>>>> a['age']
KeyError: 'nokey' # μλ ν€λ₯Ό μ‘°νν λ getλ°©μμ Noneμ λ°ν, a['sex']λ Key μ€λ₯ λ°μ!
5. λμ λ리 λΉμ°κΈ°(clear)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> a.clear()
>>>> a
{}
6. Key μ²΄ν¬ νκΈ°(in)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> 'name' in a
True
>>>> 'age'
False
7. λμ λ리 볡μ¬(dict, copy)
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> b = a
>>>> a['name'] = 'david'
>>>> b
{'name' : 'david', 'phone':'1313414', 'birth': '0819'} # dict1 = dict2μ κ²½μ° λ λ³μμ λ©λͺ¨λ¦¬ μ£Όμκ° λμΌν¨
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> c = dict(a)
>>>> a['name'] = 'david'
{'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'} # dict(a)μ κ²½μ° aκ° λ³΅μ¬λκΈ° λλ¬Έμ μλ‘ λ€λ₯Έ λ©λͺ¨λ¦¬ μ£Όμ
>>>> a = {'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'}
>>>> d = a.copy()
>>>> a['name'] = 'david'
{'name' : 'seoarang', 'phone':'1313414', 'birth': '0819'} # a.copy()μ κ²½μ° aκ° λ³΅μ¬λκΈ° λλ¬Έμ μλ‘ λ€λ₯Έ λ©λͺ¨λ¦¬ μ£Όμ
8. μ΅λκ°, μ΅μκ°, ν©(max, min, sum)
# Keyκ° κΈ°μ€μΌλ‘ μ΅λκ°, μ΅μκ°, ν© λ°ν
>>>> a = {1 :'a', 2 : 'b', 3 : 'c'}
>>>> max(a)
3
>>> min(a)
1
>>>> sum(a)
6
>>>> a = {'a' : 1, 'b' : 2, 'c' : 3}
>>>> max(a)
'c'
>>> min(a)
'a'
>>>> sum(a)
TypeError : unsupported operand type(s) for +: 'int' and 'str'
μ°Έκ³ : μ ν ν¬ νμ΄μ¬