728x90
반응형
SMALL
1. 딕셔너리(Dictionary)
- 대응관계를 나타내는 자료형으로 key와 value라는 것을 한 쌍으로 갖는 형태
- 하나의 딕셔너리의 key는 중복될 수 없다.
- 하나의 딕셔너리의 value는 중복될 수 있음.
1-1. 딕셔너리 만들기
변수 = {키1: 값1, 키2: 값2....}
dic1 = {} # 빈 딕셔너리를 생성
print(dic1)
{}
# key에 다양한 여러가지 객체가 들어가기 가능
dic2 = {1:"김사과", 2:"반하나", 3: "오렌지", 4: "이메론"}
print(dic2)
{1: '김사과', 2: '반하나', 3: '오렌지', 4: '이메론'}
1-2. key를 통해 value찾기
dic2 = {1:"김사과", 2:"반하나", 3: "오렌지", 4: "이메론"}
# [1]은 키이지 인덱스가 아님
print(dic2[1])
김사과
dic3 = {"no": 1, "userid": 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
print(dic3['no'])
print(dic3['userid'])
1
apple
1-3. 데이터 추가 및 삭제
dic4 = {1:'apple'}
print(dic4)
# 데이터 추가
dic4[100] = 'orange'
print(dic4)
dic4[50] = 'melon'
print(dic4)
print(type(dic4))
# 삭제
del dic4[1]
print(dic4)
{1: 'apple'}
{1: 'apple', 100: 'orange'}
{1: 'apple', 100: 'orange', 50: 'melon'}
<class 'dict'>
{100: 'orange', 50: 'melon'}
1-4. 딕셔너리 함수
dic3 = {"no": 1, "userid": 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
# keys(): key의 리스트를 반환
print(dic3.keys())
# values(): value 리스트를 반환
print(dic3.values())
# items(): key와 value를 한쌍으로 묶는 튜플을 반환
print(dic3.items())
# get(): key를 이용해서 value를 반환
print(dic3.get('userid'))
dict_keys(['no', 'userid', 'name', 'hp'])
dict_values([1, 'apple', '김사과', '010-1111-1111'])
dict_items([('no', 1), ('userid', 'apple'), ('name', '김사과'), ('hp', '010-1111-1111')])
apple
print(dic3["age"]) # KeyError: 'age' 키가 없으면 에러
print(dic3.get('age')) # 키가 없으면 None 출력
print(dic3.get('age', '나이를 알수없음')) # None이 출력될때 대체할수 있는 값을 입력할수 있다.
None
나이를 알수없음
# in: key가 딕셔너리 안에 있는지 확인 Object class 이다
print('name' in dic3) # True
print('age' in dic3) # False
True
False
1-5. 반복문을 이용한 딕셔너리 활용
dic3 = {"no": 1, "userid": 'apple', 'name': '김사과', 'hp': '010-1111-1111'}
for i in dic3:
print(i, end=" ") # 키만 복사해옴
no userid name hp
for i in dic3.keys():
print(i, end=" ") # 키만 복사해옴
no userid name hp
for i in dic3.values():
print(i, end=' ') # value만 복사
# 키를 찾을수 없는 방법이라 잘 사용안함
1 apple 김사과 010-1111-1111
for i in dic3:
print(dic3[i], end=" ") # 키를 가져와서 value를 반환
1 apple 김사과 010-1111-1111
1 apple 김사과 010-1111-1111
찾지 못했습니다.
key: userid values: apple
찾지 못했습니다.
찾지 못했습니다.
728x90
반응형
LIST
'파이썬' 카테고리의 다른 글
| 사용자 정의 함수(함수만들기) (0) | 2023.03.09 |
|---|---|
| 세트(set) (0) | 2023.03.08 |
| 제어문- 반복문(while, for) (0) | 2023.03.07 |
| 제어문- 조건문(if 함수) (0) | 2023.03.07 |
| 튜플(Tuple) (0) | 2023.03.07 |