강의영상

- (1/4) 딕셔너리 연산, 메소드

- (2/4) 딕셔너리 연산, 메소드 (2)

- (3/4) 딕셔너리 고급

- (4/4) 집합

딕셔너리

연산

- 하나있어요..

score = {'guebin':49, 'iu':80} 
score 
{'guebin': 49, 'iu': 80}
'guebin' in score
True
'iu' in score
True
'hynn' in score
False

- in은 사실 다른자료형도 가능했음

(관찰1)

'a' in 'guebin' 
False
'b' in 'guebin' 
True
'c' in 'guebin' 
False

(관찰2)

tpl = 1,2,3 
tpl
(1, 2, 3)
1 in tpl
True
4 in tpl
False

(관찰3)

score = [['guebin',49],['iu',80],['hynn',99]] 
score
[['guebin', 49], ['iu', 80], ['hynn', 99]]
['guebin',49] in score 
True

- in연산자가 dict형에 사용되면 key를 기준으로 True, False를 판단한다.

메소드

(get)

score = {'guebin':49, 'iu':80} 
score 
{'guebin': 49, 'iu': 80}
score.get('guebin') 
49

아래와 같은 기능

score['guebin']
49

미묘한 차이점이 존재함

score['hynn'] # hynn이 없어서 키에러 출력, 그런 key는 없다.. 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [17], in <cell line: 1>()
----> 1 score['hynn']

KeyError: 'hynn'
score.get('hynn') # hynn이 없으면 아무것도 출력안함 

(keys,values,items)

- .keys()는 딕셔너리의 키를 리턴한다.

score = {'guebin':49, 'iu':80} 
score 
{'guebin': 49, 'iu': 80}
_keys=score.keys()
_keys
dict_keys(['guebin', 'iu'])
type(_keys) # 리턴된 자료형은 이상한것임
dict_keys
list(_keys) # 아무튼 그 이상한 자료형도 리스트화 가능 
['guebin', 'iu']

- .values()는 딕셔너리의 값들을 리턴한다.

_values =score.values()
_values 
dict_values([49, 80])
type(_values)
dict_values
list(_values)
[49, 80]

- .items()는 딕셔너리의 (키,값)을 리턴한다.

_items = score.items()
_items 
dict_items([('guebin', 49), ('iu', 80)])
type(_items)
dict_items
list(_items)
[('guebin', 49), ('iu', 80)]

- for문에서의 dict

(예시1)

for i in score.keys():
    print(i)
guebin
iu
for i in score:
    print(i)
guebin
iu
  • 딕셔너리 그자체도 for문에 넣을 수 있다.
  • i에는 value가 삭제되어 들어간다. (즉 key만)
  • 결과를 보면 score대신에 score.keys()와 list(score)를 넣었을때와 결과가 같다.

Note: list(score) 하면 key만 리턴된다.

(예시2)

for i in score.values():
    print(i)
49
80

(예시3)

for k in score.items():
    print(k)
('guebin', 49)
('iu', 80)

(예시4)

for i,j in score.items():
    print(i,j)
guebin 49
iu 80

(예시5)

for i,j in score.items():
    print(i + '의 중간고사 점수는 %s점 입니다.' % j)
guebin의 중간고사 점수는 49점 입니다.
iu의 중간고사 점수는 80점 입니다.

[보충학습] 문자열 새치기

'제 이름은 %s입니다' % '최규빈'
'제 이름은 최규빈입니다'
  • %는 새치기연산자임. %s는 새치기하는 자리라고 생각

보충학습끝

딕셔너리 고급

키는 문자열만 가능한 것이 아니다.

- 정수키

score = {0:49, 1:80, 2:99} # key를 0,1,2로 
score
{0: 49, 1: 80, 2: 99}

- 인덱싱은?

score[0] # 키로 인덱싱을 하고 있는데 마치 원소의 위치로 인덱싱을 하는 기분 
49

- 그럼 혹시 이것도?

score[:2]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [79], in <cell line: 1>()
----> 1 score[:2]

TypeError: unhashable type: 'slice'
score[-1] # 이것도 될리가 없죠.. 
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
Input In [81], in <cell line: 1>()
----> 1 score[-1]

KeyError: -1

키로가능한것? 문자열, 숫자값, 튜플

score = {('guebin',0): 10, ('guebin',1): 20, ('guebin',2):49}  # 0은 출석점수, 1은 레포트 점수, 2는 중간고사 점수 
score
{('guebin', 0): 10, ('guebin', 1): 20, ('guebin', 2): 49}
score[('guebin',0)]
10
score['guebin',2]
49
score[('guebin',3)] = 99 # 규빈의 기말고사 점수를 추가 
score
{('guebin', 0): 10, ('guebin', 1): 20, ('guebin', 2): 49, ('guebin', 3): 99}
  • 문자열, 숫자값, 튜플의 공통점? 불변객체

참고 (불변형과 가변형)

(인트형은 불변)

a=1
a,id(a)
(1, 140554269835504)
a=2
a,id(a)
(2, 140554269835536)

(문자열도 불변)

a='guebin'
a,id(a)
('guebin', 140553659148336)
a='Guebin'
a,id(a)
('Guebin', 140553649883440)

(리스트는 가변)

a=list('guebin')
a,id(a)
(['g', 'u', 'e', 'b', 'i', 'n'], 140553645841408)
a[0]='G'
a,id(a)
(['G', 'u', 'e', 'b', 'i', 'n'], 140553645841408)

집합

선언

a={'notebook','desktop'}

원소추출

- 일단 인덱스로는 못합니다.

a={'notebook','desktop'}
a[0]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [132], in <cell line: 2>()
      1 a={'notebook','desktop'}
----> 2 a[0]

TypeError: 'set' object is not subscriptable

- 딱히 하는 방법이 없어요.. 그리고 이걸 하는 의미가 없어요.. (원소에 접근해서 뭐하려고??)

원소추가

- 이건 의미가 있죠

a={'notebook','desktop'} 
a
{'desktop', 'notebook'}
a.add('ipad')
a
{'desktop', 'ipad', 'notebook'}
a.add('notebook') # 이미 원소로 있는건 추가되지 않음. 
a
{'desktop', 'ipad', 'notebook'}

원소삭제

a={'desktop', 'ipad', 'notebook'}
a
{'desktop', 'ipad', 'notebook'}
a.remove('notebook')
a
{'desktop', 'ipad'}

연산

- in 연산자

a={'desktop', 'ipad', 'notebook'}
a
{'desktop', 'ipad', 'notebook'}
'notebook' in a
True
  • 참고로 in연산자는 집합에서만 쓰는것은 아님

- 합집합, 교집합, 차집합

day1 = {'notebook','desktop'}
day2 = {'notebook','ipad'}
day1 | day2 # 합집합
{'desktop', 'ipad', 'notebook'}
day1 & day2 # 교집합
{'notebook'}
day1 - day2 # 차집합 
{'desktop'}
day2 - day1 # 차집합
{'ipad'}

- 부분집합

day1 = {'notebook', 'desktop'}
day2 = day1 | {'ipad'} 
day1 < day2  # day1는 day2의 부분집합인가? 
True
day2 < day1
False

메소드

- 합집합

day1 = {'notebook', 'desktop'}
day2 = {'notebook','ipad'}
day1.union(day2)
{'desktop', 'ipad', 'notebook'}

- 나머지 메소드는 스스로 찾아보세요

for문

day1 = {'notebook', 'desktop'}
day2 = {'notebook','ipad'}
for i in day1|day2: 
    print(i)
ipad
notebook
desktop

숙제

길이가 4인 집합을 두개만들고 공통원소를 2개로 설정한뒤 합집합을 구하는 코드를 작성하라.