[Python] 딕셔너리 (Dictionary)

형이·2023년 11월 7일

Python

목록 보기
11/34
post-thumbnail

📝 딕셔너리 (Dictionary)

🖥️ 1. 딕셔너리란?

  • 대응관계를 나타내는 자료형으로 keyvalue라는 것을 한쌍으로 갖는 형태
  • 하나의 딕셔너리의 키값은 중복될 수 없음
  • 하나의 딕셔너리의 값은 중복될 수 있음

1-1. 딕셔너리 만들기

dic1 = { }
print(dic1)

dic2 = {'no' : 1, 'userid' : 'apple', 'name' : '자바학생', 'hp' : '010-1234-5678'}
print(dic2)

[결과]
{}
{'no': 1, 'userid': 'apple', 'name': '자바학생', 'hp': '010-1234-5678'}

1-2. 키로 값 찾기

dic2 = {'no' : 1, 'userid' : 'apple', 'name' : '김자바', 'hp' : '010-1234-5678'}

print(dic2['no'])
print(dic2['userid'])
print(dic2['name'])
print(dic2['hp'])

[결과]
1
apple
김자바
010-1234-5678

1-3. 데이터 추가 및 삭제

dic3 = {1:'admin'}
print(dic3)

dic3[100] = '김자바'
print(dic3)

dic3[50] = '김자바'
print(dic3)

dic3[1] = 'user'
print(dic3)

del dic3[50]
print(dic3)

print(type(dic3))

[결과]
{1: 'admin'}
{1: 'admin', 100: '김자바'}
{1: 'admin', 100: '김자바', 50: '김자바'}
{1: 'user', 100: '김자바', 50: '김자바'}
{1: 'user', 100: '김자바'}
<class 'dict'>

1-4. 딕셔너리 함수

  • keys() : key 리스트를 반환
  • values() : value 리스트를 반환
  • items() : key와 value를 한 쌍으로 묶는 튜플을 반환
  • get() : key를 이용해서 value를 반환
  • in : key가 딕셔너리 안에 있는지 확인
dic2 = {'no' : 1, 'userid' : 'apple', 'name' : '김자바', 'hp' : '010-1234-5678'}

print(dic2.keys())
print(dic2.values())
print(dic2.items())

print(dic2['userid'])    # apple
# print(dic2['age'])     # KeyError: 'age'
print(dic2.get('userid'))
print(dic2.get('age'))   # None (에러가 나지 않음)
print(dic2.get('age', '알 수 없음'))

print('name' in dic2)   # True
print('age' in dic2)    # False

[결과]

dict_keys(['no', 'userid', 'name', 'hp'])
dict_values([1, 'apple', '김자바', '010-1234-5678'])
dict_items([('no', 1), ('userid', 'apple'), ('name', '김자바'), ('hp', '010-1234-5678')])
apple
apple
None
알 수 없음
True
False

1-5. 딕셔너리와 for문

dic2 = {'no' : 1, 'userid' : 'apple', 'name' : '김자바', 'hp' : '010-1234-5678'}

for i in dic2 :   # 키만 복사
  print(i, end=' ')
print()

for i in dic2.keys() :
  print(i, end=' ')
print()

for i in dic2 :
  print(dic2[i], end=' ')
print()

for i in dic2 :
  print(dic2.get(i), end=' ')
print()

[결과]
no userid name hp 
no userid name hp 
1 apple 김자바 010-1234-5678 
1 apple 김자바 010-1234-5678 
dic2 = {'no' : 1, 'userid' : 'apple', 'name' : '김자바', 'hp' : '010-1234-5678'}

# 반복문 apple 찾으면 print로 "찾았다" 출력
for i in dic2 :
  if dic2.get(i) == 'apple' :
    print("찾았다")
    
[결과]
찾았다

📝 문제

아래와 같이 딕셔너리 자료에서 주민등록번호를 추출하여 성별을 알아내는 프로그램을 작성해보자.
(단, ssn의 7번째 자리의 성별은 1, 3은 남자고 2,4는 여자이다)

user = {"name" : "김자바", "hp" : "010-1111-1111", "ssn" : "0010114068518"}

user = {"name" : "김자바", "hp" : "010-1111-1111", "ssn" : "0010114068518"}

ssn = user.get("ssn")

if ssn[6] == '1' or ssn[6] == '3' :
  print("남자")
elif  ssn[6] == '2' or ssn[6] == '4' :
  print("여자")

[결과]
여자

0개의 댓글