새소식

언어/python

딕셔너리

  • -

안녕하세요 lika-7입니다

이번시간에는 딕셔너리에 대해서 다루겠습니다.

리스트와 딕셔너리 비교

  • 리스트는 인덱스를 기반으로 값을 저장
  • 딕셔너리는 키를 기반으로 값을 저장

딕셔너리 선언하기

dict_a = {
	"name": "어벤저스 엔드게임",
	"type": "히어로 무비"
}

딕셔너리 접근하기

dict_a = {
	"name": "어벤저스 엔드게임",
	"type": "히어로 무비"
}

dict_a["type"]

리스트 처럼 대괄호를 이용하여 접근합니다.

dict_a = {
    "name": "7D 건조 망고",
    "type": "당절임",
    "ingredient": ["망고", "설탕", "메타중아황산나트륨", "치자황색소"],
    "origin": "필리핀"
}

print("name:", dict_a["name"])
print("ingredient:", dict_a["ingredient"][0])

name: 7D 건조 망고
ingredient: 망고

딕셔너리에 값 추가하기

dictionary["name"] = "8D 건조 파인애플"

딕셔너리 요소 제거하기

dictionary = {
	"name": "8D 건조 파인애플",\
	"type": "당절임"
}

del dictionary["name"]

print("dictionary:",dictionary)

dictionary: {'type': '당절임'}

get( ) 함수

존재하니 않는 키에 접근하는 방법

dictionary = {
	"name": "8D 건조 파인애플",
	"type": "당절임"
}

value = dictionary.get("name", "not in dicdictionary")

print("value:",value)

키가 있다면 value: 8D 건조 파인애플 반환

dictionary = {
	"name": "8D 건조 파인애플",
	"type": "당절임"
}

value = dictionary.get("name1", "not in dictionary")

print("value:",value)

키가 없다면 value: not in dictionary 반환

'언어 > python' 카테고리의 다른 글

while 반복문  (0) 2023.12.17
for 반복문  (0) 2023.12.17
리스트 제거  (0) 2023.12.17
append, insert  (0) 2023.12.17
pass 키워드, raise NotImplementError  (0) 2023.12.17
Contents

포스팅 주소를 복사했습니다

이 글이 도움이 되었다면 공감 부탁드립니다.