[딕셔너리 자료형]
- 딕셔너리 자료형의 Key 값은 중복되면 X, Value는 중복 가능
[딕셔너리 쌍 추가하기]
- {1: 'a'}에 {2: 'b'}, {'name': 'Polibo'}, 그리고 {3: [1, 2, 3]} 딕셔너리 쌍 추가하기
print("----------[ 딕셔너리 쌍 추가하기 ]----------")
dict_1 = {1: 'a'}
dict_1[2] = 'b'
print(dict_1)
dict_1['name'] = 'Polibo'
print(dict_1)
dict_1[3] = [1, 2, 3]
print(dict_1)
[딕셔너리를 사용하는 방법]
- 딕셔너리에서 Key를 사용해 Value 얻기
- Key가 문자, 숫자인 경우와 상관없이 Value 값 얻을 수 있음.
print("----------딕셔너리에서 Key를 사용해 Value 얻기----------")
dict_1 = {'pey': 10, 'julliet': 99}
print(dict_1['pey'])
print(dict_1['julliet'])
dict_2 = {1: '1번', 2: '2번', 3: 3}
print(dict_2[2])
print(dict_2[3])
[딕셔너리 관련 함수]
- keys : Key 리스트 만들기
- keys와 values는 iterative 하지만, subscriptable 하지 않음 => 인덱싱이 불가능함. but, 반복문 가능.
- dict_keys 객체를 list 함수를 사용하여 list화 가능
- Key인 'name', 'height', 'birth'가 출력됨.
print("----------[ Key 리스트 만들기 - keys ]----------")
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
print(dict_1.keys())
print(list(dict_1.keys())) # dict_keys 객체를 list로 변환
- values : Value 리스트 만들기
- dict_values 객체를 list 함수를 사용하여 list화 가능
- Value인 'Polibo', 168, '6월14일'이 출력됨.
print("----------[ Value 리스트 만들기 - values ]----------")
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
print(dict_1.values())
print(list(dict_1.values()))
- items : Key, Value 쌍 얻기
- list 함수 사용하여 list화 가능
- 3개의 Key, Value 쌍이 출력됨.
print("----------[ Key, Value 쌍 얻기 - items ]----------")
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
print(dict_1.items())
print(list(dict_1.items()))
- get : Key로 Value 얻기
- 함수를 쓰지 않고 그냥 dict_1('name')으로도 Value를 얻을 수 있음.
- get 함수의 default가 존재하지 않는 Key로 Value를 얻으려고 할 때, None을 출력하는 것임. 이것을 바꿔줄 수 있음.
- 두 개의 다른 점은 존재하지 않는 Key로 Value을 얻으려고 할 때, dict_1('..') 방식은 오류가 발생하고, dict_1.get('..")은 None이 출력된다는 것임.
print("----------[ Key로 Value 얻기 - get ]----------")
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
print(dict_1.get('name'))
print(dict_1.get('height'))
print(dict_1.get('birth'))
print(dict_1.get('address', 'Gwangju')) # dict_1에 'address'에 해당하는 Key가 없으면 default 값인 'Gwangju'를 리턴함.
print(dict_1['phone']) # 없는 Key 값을 넣었을 때, 오류 발생
print(dict_1.get('phone')) # 없는 Key 값을 넣었을 때, None이 리턴됨.
- in : 해당 Key가 딕셔너리 안에 있는지 조사하기
- 있으면 True / 없으면 False를 출력함.
- 응용하여 for문으로 2개의 변수를 출력할 수 있음.
print("----------[ 해당 Key가 딕셔너리 안에 있는지 조사하기 - in ]----------")
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
print('name' in dict_1)
print('weight' in dict_1)
dict_1 = {'name': 'Polibo', 'height': 168, 'birth': '6월14일'}
for k, v in dict_1.items():
print(k, v)
'Python' 카테고리의 다른 글
[2025.02.25] 모듈 (0) | 2025.02.25 |
---|---|
[2025.02.25] 집합 자료형, 불 자료형 (0) | 2025.02.25 |
[2025.02.25] 튜플 자료형 (0) | 2025.02.25 |
[2025.02.25] 리스트 자료형 (0) | 2025.02.25 |
[2025.02.24] for문_별찍기 (0) | 2025.02.24 |