9.1 dictionaries
정의 자체는
key와 value가 짝을 지어서 ,로 구분된 자료형태이다. 이름과 같이 사전과 같은 형태를 가지고 있다.
대괄호 말고 {} 중괄호를 사용한다.
dictionaries 자체는 mutable.(key를 바꿀 수는 없음)
value와 key로 구성된다. <<<--- 기말고사 이거 틀려서 매우 웃겼다. 사실 안웃겨
*key 는 unique 하고 immutable하다!!!!
*values cannot exist without a key
value 에 list가 들아간다고 보면 된다.
stuff = {'hello' : 'Hello there, how are you?', 'chat' : 'How is the weather?',
'goodbye' : 'It was nice to talk to you!'}
>>> stuff['hello']
'Hello there, how are you?'
>>> stuff['chat']
'How is the weather?'
>>> stuff['goodbye']
'It was nice to talk to you!'
* len(stuff) 는 3이다.
key 에는 문자열도 들어갈 수 있고, 숫자도 들어갈 수 있다. 어떤 데이터 종류이든 상관없다.
인덱스가 아니라 key 값을 [] 안에 넣어준다는 걸 기억해줘야 한다.
리스트처럼 인덱싱되지 않는다.

Dictionaries 는 순서가 정해져 있지 않다. 반면, list 는 순서가 부여되어 있다.
favorites1 = {'fruit' : 'apples', 'number' : 42}
favorites2 = {'number' : 42, 'fruit' : 'apples'}
favorites1 == favorites2
True
fav1 = ['apples', 42]
fav2 = [42, 'apples']
fav1 == fav2 #False
리스트가 value로 들어가는 게 이해되지 않을까 싶어 추가해봤다.
a = [1,2,3,4,5]
dict_a = {'a_dict' : a}
print(dict_a['a_dict']) #1,2,3,4,5
9.2 keys(), values()
values는 key를 통해 찾을 수 있고 key를 이용하여 접근할 수 있지만,
또한, key 없이 value가 존재할 수 없다.
key는 unique한 값이고 바뀔 수 없다.
- value는 key를 통해 찾을 수 있고, key를 이용하여 접근할 수 있지만, value를 통해 key를 찾는 것은 불가능하다.
- key 없이 value가 존재할 수 없다.
- key는 unique한 값이기 때문에 중복되면 맨 위만 탐지한다.
- key는 바뀔 수 없다(immutable). 변하면 오류가 발생하기 때문에 변경 불가능한 상수 혹은 문자로 해두는 것이 좋다.
- value는 바뀌어도 괜찮다. dictionary에 저장된 것이 변하는 것이 아니다.
dictionaries에서 key들만 모여있는 list를 불러오고 싶으면
dictionaries.keys()
value들만 모여있는 list를 불러오고 싶으면
dictionaries.values() 를 해주면 된다.

9.3 Altering a dictionary (update, pop)
can be done via dictionary methods
favorites = {'fruit' : 'apples', 'number' : 42}
favorites.update({'season' : 'winter'})
print(favorites) # {'fruit' : 'apples', 'number' : 42, 'season' : 'winter'}
favorites.pop('fruit')
print(favorites) # {'number' : 42, 'season' : 'winter'}
9.4 Define defalut values in Dictionaries 딕셔너리에서 디폴트 값 정의하기
.get()
.setdefault()
get() 함수를 사용하면 dictionary에 그 값이 있는지 찾을 수 있다.
원하는 값을 넣었을 때 그 key 가 dictionary에 있으면 value를 반환해주고, 없으면 None을 반환해준다.
my_dict = {"item":"football", "price":10.00}
# count = my_dict["count"] 이 줄 있으면 KeyError 발생한다.
count = my_dict.get("count")
count = my_dict.get("count",0) # 여기 0에 다른 숫자 집어넣으면 그 숫자가 나온다.
print(count)
print(my_dict)
count = my_dict.setdefault("count",0)
print(count)
print(my_dict)
0
{'item': 'football', 'price': 10.0}
0
{'item': 'football', 'price': 10.0, 'count': 0}
setdefault() 함수는
d.setdefault(a,b) 를 입력하면 d라는 dictionary에
a라는 key가 있으면 d[a]를 반환하고,
a라는 key가 없으면 d에 {a:b}를 추가한다.
'프로그래밍 > python' 카테고리의 다른 글
11. Ternary conditional operator, underscore, context manager, with (0) | 2021.12.30 |
---|---|
10. tuples, sets (0) | 2021.12.30 |
8. ASCII art, list (in, del, list of list, split, reverse, append, remove, len, sort, sorted) (0) | 2021.12.29 |
7. lower(), upper(), recursive function (0) | 2021.12.29 |
6. function definition, function call, local/global variables (import time) (0) | 2021.12.29 |