728x90
딕셔너리(dictionary)
👉'키(key)와 '값(value)'으로 이루어져있다.
- 키를 이용하여 값(데이터)를 저장한다.
- 키를 이용하여 값(데이터)를 찾는다.
❔리스트와 다른점
값을 저장하거나 기르킬 경우
- 리스트 → '인덱스'기반
- 딕셔너리 → '키' 기반
선언하기
1. 비어있는 딕셔너리 선언
dic = {}
2. key : value 선언
key 1개당 value를 1개를 갖는다.
# 기본적인 형태
dic1={'key':'value'}
# 예시
dic={'사과':'apple', '바나나':'banana', '오렌지':'orange'}
3. key : list 선언
key1 개당 여러개의 value를 list를 통해 저장할 수 있다.
value부분에 리스트 형태로 값을 넣어주면 된다.
# key와 list
dic1={'key':['value1', 'value2'])
# 예시
dic2={'fruit':['apple', 'banana', 'orange']}
4. 주의사항
1) key는 list로 선언할 수 없다
dic={['apple', 'banana', 'orange']:'fruit'}
❌TypeError: unhashable type: 'list'
2) 키를 문자열로 사용시 따옴표를 쓰지 않는 경우
dic={fruit:'apple'}
❌ NameError: name 'friut' is not defined
요소에 접근하기 및 출력
딕셔너리[접근하려는 키]
요소가 한 개인 경우 또는 해당 요소 전체 출력
딕셔너리에 사용된 key를 사용하여 요소에 접근할 수 있다.
# 딕셔너리 선언
dic={
'food':'sandwich',
'price':'3000'}
# 딕셔너리 출력
print(dic)
print("food name:", dic['food'])
print("price:",dic['price'])
> 출력결과
#출력결과
{'food': 'sandwich', 'price': '3000'}
food name: sandwich
price: 3000
값이 리스트 형태인 경우
딕셔너리의 키를 통해 값인 리스트 전체를 출력할 수 있다.
또는 인덱스를 지정해서 리스트 안의 값을 출력할 수 있다.
# # 딕셔너리 선언
dic={
'food':'sandwich',
'price':'3000',
'ingredients':['bread', 'lettuce','cheese','ham']}
# 딕셔너리 출력
# 리스트 전체 출력
print("ingredients: ", dic['ingredients'])
# 리스트 값중 하나 출력
print("ingredients[0]: ", dic['ingredients'][0])
print("ingredients[1]: ", dic['ingredients'][1])
print("ingredients[2]: ", dic['ingredients'][2])
print("ingredients[3]: ", dic['ingredients'][3])
> 출력결과
ingredients: ['bread', 'lettuce', 'cheese', 'ham']
ingredients[0]: bread
ingredients[1]: lettuce
ingredients[2]: cheese
ingredients[3]: ham
추가하기
딕셔너리[추가할 키] = 값
dic={}
dic["name"]="cheolsu"
dic["age"]="20"
삭제하기
del 딕셔너리[삭제할 키]
dic={'사과':'apple', '바나나':'banana', '오렌지':'orange'}
# {'바나나':'banana'} 삭제
del dic['바나나']
수정하기
방법은 추가하기와 동일하다. 키를 적는 곳에 이미 선언된 키를 지정하면 해당 키의 값을 수정한다.
dic={'name':'cheolsu', 'age':'20'}
# age의 값을 20에서 21로 수정
dic["age"]="21"
728x90
'LANGUAGE > Python' 카테고리의 다른 글
[python] 파이썬 파스칼 삼각형(Pascal's triangle) 만들기 (1) | 2023.10.24 |
---|---|
[Python] 파이썬 주석처리 하는 법 (0) | 2022.07.04 |