dictionary
key 기반으로 값 저장하는 배열
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
# 딕셔너리 선언
dictionary = {"key" : "value1", "key2" : "value2", "key3" : "value3" }
# key로 value에 접근
dictionary["key2"]
'value2'
# 딕셔너리 출력
dictionary
{'key': 'value1', 'key2': 'value2', 'key3': 'value3'}
# value에 리스트, 딕셔너리도 가능
dic = {"key" : "value1", "key2" : ['you','can','use','list','in','dictionary']}
dic["key"]
'value1'
dic["key2"]
['you', 'can', 'use', 'list', 'in', 'dictionary']
# 딕셔너리 내 리스트 특정 인덱스 접근
dic["key2"][1]
'can'
|
cs |
딕셔너리 요소 추가 : 딕셔너리이름.[새로운 키] = 새로운 값
딕셔너리 요소 제거 : del 딕셔너리이름[지울 키]
키 존재 여부 확인 : 키 in 딕셔너리명
예) if key in dic:
딕셔너리 for 반복문
1
2
3
4
5
6
7
8
|
dic = {"key" : "value1", "key2" : ['you','can','use','list','in','dictionary']}
for key in dic:
print( key, " : ", dic[key])
# 출력 결과
key : value1
key2 : ['you', 'can', 'use', 'list', 'in', 'dictionary']
|
cs |
items()
dictionary의 키와 값을 조합해 출력하기 쉬운 형태로 변환하는 함수
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
sample_dictionary = {
"key A" : "value A",
"key B" : "value B",
"key C" : "value C"
}
print(sample_dictionary)
# ↑ 출력 : {'key A': 'value A', 'key B': 'value B', 'key C': 'value C'}
print(sample_dictionary.items())
# ↑ 출력 : dict_items([('key A', 'value A'), ('key B', 'value B'), ('key C', 'value C')])
for key, element in sample_dictionary.items():
print('sam_dic[{}] = {}'.format(key, element))
# ↑ 출력 : sam_dic[key A] = value A
# sam_dic[key B] = value B
# sam_dic[key C] = value C
|
cs |
sample_dictionary 를 출력한 것과 (8번째 줄)
sample_dictionary.items() 를 출력한 형태가 다르다. (11번째 줄)
items() 함수를 for문에서 사용하면 키와 값을 매치해서 쉽게 출력할 수 있다.
'프로그래밍 > Python' 카테고리의 다른 글
프로그래머스_python lv0. 문자열 뒤집기 (0) | 2023.01.20 |
---|---|
파이썬 개념 - 리스트 내포(list comprehension) (0) | 2023.01.19 |
파이썬 개념 - list와 enumerate( ) 함수 (0) | 2023.01.19 |
프로그래머스_python lv0. 배열 뒤집기 (0) | 2023.01.18 |
파이썬 개념 - range, reverse, for-continue (0) | 2023.01.17 |