딕셔너리 사용하기

Python의 데이터 타입

Jason Myers

Instructor

딕셔너리 생성 및 순회

  • 키/값 쌍으로 데이터 저장
  • 중첩 가능 (딕셔너리의 값으로 딕셔너리 사용)
  • 반복 가능
  • dict() 또는 {}로 생성
art_galleries = {}

for name, zip_code in galleries:
    art_galleries[name] = zip_code
Python의 데이터 타입

루프에서 출력하기

for name in sorted(art_galleries)[-5:]:
    print(name)
Zwirner David Gallery
Zwirner & Wirth
Zito Studio Gallery
Zetterquist Galleries
Zarre Andre Gallery
Python의 데이터 타입

키로 안전하게 조회하기

art_galleries['Louvre']
|--------------------------------------------------------------------
KeyError                            Traceback (most recent call last)
<ipython-input-1-4f51c265f287> in <module>()
--> 1 art_galleries['Louvre']

KeyError: 'Louvre'
  • 딕셔너리에서 값을 가져올 때 키를 인덱스로 사용합니다
  • 존재하지 않는 키를 요청하면 KeyError가 발생하여 프로그램이 중단됩니다
Python의 데이터 타입

키로 안전하게 조회하기 (계속)

  • .get() 메서드를 사용하면 오류 처리 없이 키에 안전하게 접근할 수 있습니다
  • 키가 없으면 기본적으로 None을 반환하거나, 반환할 값을 직접 지정할 수 있습니다
art_galleries.get('Louvre', 'Not Found')
'Not Found'
art_galleries.get('Zarre Andre Gallery')
'10011'
Python의 데이터 타입

연습해 봅시다!

Python의 데이터 타입

Preparing Video For Download...