NIRVANA
[복습] 파이썬 dictionary 본문
참고: https://docs.python.org/ko/3/tutorial/datastructures.html#dictionaries
딕셔너리(dictionary)란?
: 파이썬 자료형 중 하나. 숫자로 인덱싱 되는 시퀀스(리스트 등)와 다르게, 딕셔너리는 키로 인덱싱 된다.
이 때, 문자열 숫자 등이 키로 올 수 있으며 만약 튜플 형캐가 문자열이나 숫자로만 이루어졌을 경우 키로 사용될 수 있다.
단, 튜플이 직접적이나 간접적으로 가변 객체를 포함하면 키로 사용할 수 없다. 리스트는 역시 인덱스 대입, 슬라이스 대입, append(), extend() 같은 메서들로 수정될 수 있기 때문에 키로 사용이 불가능하다.
즉, 파이썬 딕셔너리에서 키는 가변적이지 않고 불변적인 자료형들 만이 올 수 있다.
딕셔너리에서 키는 중복될 수 없다. 중괄호 쌍 {}으로 빈 딕셔너리를 생성할 수 있으며, 중괄호 안에 쉼표로 분리 된 key: value 쌍을 넣어 딕셔너리를 만들 수 있다.
딕셔너리의 키로 value값을 불러올 수 있다.
예시)
dic_example = {
'enhypen':'engine', 'theboyz':'theb', 'ncity':'ncitizen'
}
#key를 사용해서 value값 꺼내기
for idol in dic_example:
print(dic_example[idol])
#key:value쌍 추가
dic_example['seventeen'] = 'carat'
print(dic_example)
#딕셔너리에서 key:value쌍 삭제
del dic_example['seventeen']
print(dic_example)
#딕셔너리에서 사용되고 있는 모든 키의 리스트를 삽입 순서대로 돌려주기
list(dic_example)
#딕셔너리 정렬
sorted(dic_example)
dict()를 사용하여 딕셔너리를 생성하는 것도 가능하다.
dic_example = {
'enhypen':'engine', 'theboyz':'theb', 'ncity':'ncitizen'
}
for idol in dic_example:
print(dic_example[idol])
new_dictionary = dict([('enhypen','engine'), ('theboyz', 'theb'), ('ncity', 'ncitizen')])
for i in new_dictionary:
print(new_dictionary[i])
'Coding test(Python3)' 카테고리의 다른 글
[비선형 자료구조] 힙(Heap) 정리 및 문제 풀이 (0) | 2024.06.26 |
---|