상세 컨텐츠

본문 제목

10_딕셔너리

Python/1.파이썬 문법

by 일동일동 2023. 2. 23. 11:32

본문

728x90
반응형

1. 딕셔너리(Dictionary)

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

1-1. 딕셔너리 만들기

dic1 = {} # 빈 딕셔너리를 생성
print(dic1)

{}

dic2 = {1: '김사과', 2:'반하나', 3:'오렌지', 4:'이메론'}
print(dic2)

{1: '김사과', 2: '반하나', 3: '오렌지', 4: '이메론'}

 

1-2. key를 통해 value 찾기

dic2 = {1: '김사과', 2:'반하나', 3:'오렌지', 4:'이메론'}
print(dic2[1])
print(dic2[3])

김사과

오렌지

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'    # 100은 key 값, orange는 value 값
print(dic4)

dic4[50] = 'melon'
print(dic4)

print(type(dic4))

{1: 'apple'}

{1: 'apple', 100: 'orange'}

{1: 'apple', 100: 'orange', 50: 'melon'}

<class 'dict'>

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())

print(dic3['userid'])

# get(): key를 이용해서 value를 반환
print(dic3.get('userid'))

# 키가 존재하지 않으면 에러
# print(dic3.get['age'])
print(dic3.get('age')) # None
print(dic3.get('age', '나이를 알 수 없음'))

# in: key가 딕셔너리 안에 있는지 확인
print('name' in dic3) # True
print('age' in dic3) # False

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

apple

None

나이를 알 수 없음

True

False

1-5. 딕셔너리와 for

dic3 = {'no':1, 'userid' : 'apple', 'name' : '김사과', 'hp' : '010-1111-1111'}

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

print()

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

print()

for i in dic3.values():
    print(i, end=' ') # 값만 복사

print()

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

print()

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

print()

no userid name hp

no userid name hp

1 apple 김사과 010-1111-1111

1 apple 김사과 010-1111-1111

1 apple 김사과 010-1111-1111

 

dic3 = {'no':1, 'userid' : 'apple', 'name' : '김사과', 'hp' : '010-1111-1111'}

for i in dic3.keys():
    if dic3.get(i) == 'apple':
        print('찾았습니다! apple')
    else:
        print('못찾았습니다!')

못찾았습니다!

찾았습니다! apple

못찾았습니다!

못찾았습니다!

 

반응형

'Python > 1.파이썬 문법' 카테고리의 다른 글

12_재귀호출  (0) 2023.02.23
11_기본정렬  (0) 2023.02.23
9_제어문(반복문)  (0) 2023.02.23
8_제어문(조건문)  (1) 2023.02.19
7_해쉬 테이블  (0) 2023.02.19

관련글 더보기