[제로베이스] [자료 구조] 튜플 & 딕셔너리

한결·2023년 12월 20일
0
post-thumbnail

1. 튜플

튜플
리스트와 비슷하지만 아이템 변경이 불가능하다.

tuple1 = (1,2,3,4,5)

✅ 튜플은 ( )를 이용해 선언하고, 데이터 구분은 ,를 이용한다.


1-1. 튜플 아이템 조회

리스트와 마찬가지로 0번부터 차례대로 인덱스가 부여된다.

tuple1 = (1, 2, 3, 4, 5)

print(tuple1[2])
3

1-2. 존재 유무 확인

in, not in 키워드를 이용해 존재 유무를 알 수 있다.

tuple1 = (1, 2, 3, 4, 5)

if 6 in tuple1:
    print('있음')

if 6 not in tuple1:
    print('없음')
없음

1-2. 튜플의 길이

튜플의 길이는 튜플에 저장된 아이템 개수이다.

tuple1 = (1, 2, 3, 4, 5)

print(len(tuple1))
5

1-3. 튜플의 결합

튜플은 + 연산자를 이용해 결합할 수 있다.
❗ 리스트와 다르게 extend()를 사용할 수 없다.

tuple1 = (1, 2, 3, 4, 5)

tuple2 = (6,7)

print(tuple1 + tuple2)
(1, 2, 3, 4, 5, 6, 7)

1-4. 튜플 슬라이싱

[n:m]을 이용하면 튜플에서 원하는 아이템만 뽑아낼 수 있다.

tuple1 = (1, 2, 3, 4, 5)

print(tuple1[2:4])
print(tuple1[1:])
print(tuple1[:3])
(3, 4)
(2, 3, 4, 5)
(1, 2, 3)

1-5. 리스트 튜플 변환

tuple1 = (1,2,3,4,5)
tuple1 = list(tuple1) # 튜플에서 리스트로
print(tuple1)

tuple1 = tuple(tuple1) # 리스트에서 튜플로
print(tuple1)
[1, 2, 3, 4, 5]
(1, 2, 3, 4, 5)

1-6. 튜플 아이템 정렬

tuple은 list와 다르게 수정이 불가능 하기에

  • tuple을 list로 바꾼 뒤 sort()를 이용해 정렬한 뒤 다시 tuple 로 바꾼다.
  • sorted()를 이용해 리스트를 받아낸뒤 tuple 로 바꾼다.

1-7. 튜플과 for

for문을 이용해 튜플의 아이템을 자동으로 참조할 수 있다.

students = ('David','Sam','Sean','Amy')

for student in students:
	print(student)
David
Sam
Sean
Amy

for문을 이용해 튜플 내부에 또다른 튜플의 아이템을 조회할 수 있다.

students = (('David',1),('Sam',3),('Sean',4),('Amy',6))

for student, grade in students:
	print(f'이름: {student}, 학년: {grade}')
이름: David, 학년: 1
이름: Sam, 학년: 3
이름: Sean, 학년: 4
이름: Amy, 학년: 6

1-8. 튜플과 while

while문을 이용하면 다양한 방법으로 아이템 조회가 가능하다.

students = ('David','Sam','Sean','Amy')

# 1번 표현
n=0
while n<len(students):
    print(students[n])
    n += 1

# 2번 표현
n=0
flag = True
while flag:
    print(students[n])
    n += 1
    if n == len(students):
        flag = False

# 3번 표현
n=0
while True:
    print(students[n])
    n += 1
    if n == len(students):
        break

전부 같은 결과가 나온다.

David
Sam
Sean
Amy

2. 딕셔너리

딕셔너리
키(key)와 값(value)를 이용해서 자료를 관리한다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}

✅ 딕셔너리는 { }를 이용해 선언하고, '키 : 값'의 형태로 아이템을 정의한다.


2-1. 딕셔너리 조회

딕셔너리는 키(key) 또는 get()을 이용해 값(value)를 조회한다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}

print(studentScore['David'])
print(studentScore.get('Sean'))

print(studentScore.get('Jeff')) # 딕셔너리에 없는 경우 None 반환
print(studentScore['Jeff']) # 딕셔너리에 없는 경우 에러
30
70
None
Traceback (most recent call last):
  File "/Users/gyol/Documents/pythonEx/project/2-001/hello.py", line 7, in <module>
    print(studentScore['Jeff'])
          ~~~~~~~~~~~~^^^^^^^^
KeyError: 'Jeff'

2-2. 딕셔너리 추가

딕셔너리이름[키] = 값 형태로 아이템을 추가한다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}
studentScore['Paul']=35

print(studentScore)
{'David': 30, 'Sam': 20, 'Sean': 70, 'Amy': 55, 'Paul': 35}

2-3. 딕셔너리 수정

딕셔너리이름[변경할 키] = 값 형태로 아이템을 변경한다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}
studentScore['David']=35

print(studentScore)
{'David': 35, 'Sam': 20, 'Sean': 70, 'Amy': 55}

2-4. 딕셔너리 아이템 조회

keys(), values()

keys()values()를 통해 전체 키와 값을 조회할 수 있다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}

print(studentScore.keys())

print(studentScore.values())
dict_keys(['David', 'Sam', 'Sean', 'Amy'])
dict_values([30, 20, 70, 55])

2-5. 딕셔너리 아이템 삭제

del

del Dictionary[key]를 이용해 아이템을 삭제할 수 있다.

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}

del studentScore['David']

print(studentScore)
{'Sam': 20, 'Sean': 70, 'Amy': 55}

pop()

studentScore = {'David':30, 'Sam':20, 'Sean':70, 'Amy':55}

studentScore.pop('David')

print(studentScore)
{'Sam': 20, 'Sean': 70, 'Amy': 55}

2-6. 그외 기능들

in, not in : 키 존재 유/무 판단
len() : 딕셔너리의 아이템 개수를 알 수 있다.
clear() : 모든 아이템 삭제

profile
낭만젊음사랑

0개의 댓글