티스토리 뷰

1. 세트

중복되지 않는 항목들의 컬렉션

 
# 1. 생성
s1 = {}
print(s1)
print(type(s1))     # dict타입
 
s1 = {1, 3, 5, 7}
print(s1)
print(type(s1))     # set타입
 
# 2. 메소드
# add() : 셋에 항목을 추가
s1 = {100, 200}
s1.add(15)
print(s1)         # 순서가 일정하지 않음
s1.add(60)
print(s1)
 
 
# update() : 셋에 여러 항목을 한번에 추가
s1 = {100, 200}
s1.update([40, 50, 60, 20])
print(s1)
 
# remove() : 셋의 항목을 제거, 항목이 없으면 KeyError 발생
s1.remove(20)
print(s1)
 
# discard() : 셋의 항목을 제거, 항목이 없어도 에러 없음
s1 = {10, 20, 30}
s1.discard(30)
print(s1)
s1.discard(30)
print(s1)           # 에러 없음
 
# copy() : 셋 복사
s1 = {10, 20, 30}
s2 = s1.copy()
print(s1)
print(s2)
print(id(s1))
print(id(s2))     # 주소는 다름
 
 
# union() : 합집합, intersection() : 교집합, difference() : 차집합
s1 = {10, 20, 30, 40, 50}
s2 = {30, 40, 50, 60, 70}
result1 = s1.union(s2)
result2 = s1.intersection(s2)
result3 = s1.difference(s2)

print(result1)
print(result2)
print(result3)
 
# symmetric_difference() : ^연산자, 두개의 세트 대칭 차집합, 합집합-교집합
result = s1.symmetric_difference(s2)
print(result)
print(s1^s2)
 

 

2. 딕셔너리

키-값 쌍을 저장하는 변경 가능한 컬렉션

 
# 1. 생성
dic1 = {}        #빈 딕셔너리 생성
print(dic1)
 
dic2 = {1:'김사과', 2:'반하나', 3:'오렌지', 4:'이메론'}
print(dic2)
print(dic2[1])     # 김사과
print(dic2[3])    # 오렌지
 
dic3 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(dic3)
print(dic3['no'])         # 1
print(dic3['userid'])  # apple
 
# 2. 변경 가능 (키-값 추가 제거 변경)
dic1 = {1:'apple'}
print(dic1)                   # {1: 'apple'}

dic1[100] = 'orange'
print(dic1)                  # {1: 'apple', 100: 'orange'}

dic1[50] = 'melon'
print(dic1)                   # {1: 'apple', 100: 'orange', 50: 'melon'}
 
del dic1[1]
print(dic1)                   # {100: 'orange', 50: 'melon'}
 
# 3. 키, 값의 제약
# 리스트는 키로 사용 불가, 값은 상관없음
dic1 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
dic1['no'] = 10      # 원래 있던 키에 값 덮어쓰기
print(dic1)
 
dic1['점수'] = [90, 100, 50] # 새로운 키, 값 추가
print(dic1)
 
dic1[(1,2,3)] = ('⚽️','🏀','🎱') # 키 값으로 튜플 가능
print(dic1)
#dic1[[1,2,3]] = ('⚽️','🏀','🎱') # 키 값으로 리스트 불가능 TypeError: unhashable type: 'list'
dic1['스포츠'] = {'축구':'⚽️', '농구':'🏀', '볼링':'🎱'}
print(dic1)                 
# {'no': 10, 'userid': 'apple', 'name': '김사과', 'hp': '010-1111-1111', '점수': [90, 100, 50], (1, 2, 3): ('⚽️', '🏀', '🎱'), '스포츠': {'축구': '⚽️', '농구': '🏀', '볼링': '🎱'}}
 
 
# 4. 함수와 메서드
dic1 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print(len(dic1))                        # 4
print(dic1.keys())                    # keys() : 딕셔너리의 모든 키를 반환
print(dic1.items())                   # items() : 딕셔너리의 모든 키-값을 튜플로 반환
print(dic1.get('userid'))          # get() : 특정 키의 값을 반환, 없으면 None 반환
print(dic1['userid'])                 # 같은 결과
print(dic1.get('age'))
print(dic1.get('age', '나이를 알 수 없음'))
print(dic1.pop('hp'))              # pop() : 특정 키의 값을 제거하고 반환
print(dic1)                               # hp키가 제거되어있음
 
# in 연산자
dic1 = {'no':1, 'userid':'apple', 'name':'김사과', 'hp':'010-1111-1111'}
print('hp' in dic1)                  # True
print('age' in dic1)                # False
 
 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
글 보관함