How We Coding

동영상 강의 : http://pythonkim.tistory.com/notice/77



# Day_03_02_dict.py


- set 과 dictionary


1
2
3
4
5
= {}
print(type(a), a)  # <class 'dict'> {}
 
= {1}
print(type(b), b)   # <class 'set'> {1}
cs


>> 중괄호를 이용한 컬렉션은 두가지 : set 과 dictionary

>> dictionary 가 set 보다 백만배 중요하다고 한다.



- dictionary 의 초기화


1
2
= {1:2}
print(type(c), c)   # <class 'dict'> {1: 2}
cs




- Set


1
2
3
4
5
= {123123123}
print(type(d), d)   # <class 'set'> {1, 2, 3}
 
= [123123123]
print(type(e), e)   # <class 'list'> [1, 2, 3, 1, 2, 3, 1, 2, 3]
cs


>> set은 중복된 데이터를 허용하지 않는다.

>> 반면, list 는 중복된 데이터를 허용한다.



# 문제

# 리스트에 들어있는 중복된 데이터를 제거하기


1
2
3
4
5
= [123123123]
print(type(e), e)   # <class 'list'> [1, 2, 3, 1, 2, 3, 1, 2, 3]
 
= list(set(e))
print(e)            # [1, 2, 3]
cs


>> set(e) 의 결과는 set 이므로 list 로 캐스팅.



- Dictionary


- 초기화


1
2
= {'color''red''price'100}
print(d)            # {'color': 'red', 'price': 100}
cs


>> key: value 의 쌍으로 구성된다.



- 초기화 2


1
2
3
4
= dict(color='red', price=100)
print(d)            # {'color': 'red', 'price': 100}
print(d['color'])   # red
print(d['price'])   # 100
cs


>> 위와 아래의 차이점은 거의 없다고 보면 된다.

>> 아래의 방법으로 초기화 하는 것을 선호한다고 한다. dict() 함수를 이용해서 dictionary 만드는 방법

>> key 값에 ' ' 를 생략하면 자동으로 포함이 된다.

>> 리스트는 요소들의 순서가 보장되지만, 딕셔너리는 순서를 보장하지 않는다.


>> 3, 4 : dictionary 요소 접근



 - dictionary 에서 데이터 삽입


1
2
3
4
5
6
# 데이터 삽입
d['title'= 'pen'
print(d)        # {'color': 'red', 'price': 100, 'title': 'pen'}
 
d['title'= 'bread'
print(d)        # {'color': 'red', 'price': 100, 'title': 'bread'}
cs


>> 2 : insert

>> 4 : update (title 이란 키값이 이미 존재하므로..!!)

>> dictionary 는 키값의 중복을 허용하지 않는다..!!



-

1
2
3
print(d.keys())     # dict_keys(['color', 'price', 'title'])
print(d.values())   # dict_values(['red', 100, 'bread'])
print(d.items())    # dict_items([('color', 'red'), ('price', 100), ('title', 'bread')])
cs



# 문제

# keys, values, items 를 for문과 연결해서 처리해보자.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
for k in d.keys():
   print(k, d[k])
print('-'*10)
 
for v in d.values():
    print(v)
print('-'*10)
 
for i in d.items():
    print(i, i[0], i[1])
print('-'*10)
 
for k, v in d.items():
    print(k, v)
cs


>> 2 : 키값을 통해 value 를 알 수 있다.

>> 5 : value 만으로는 아무것도 할 수 없다.

>> 9 : i 의 결과는 튜플이다. 그렇기 때문데, 13-14와 같은 형태로 이용을 한다.


>> 실행결과

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
color red
price 100
title bread
----------
red
100
bread
----------
('color', 'red') color red
('price', 100) price 100
('title', 'bread') title bread
----------
color red
price 100
title bread
cs

  


- enumerate()


1
2
for i in enumerate(d.items()):
    print(i)
cs


>> 인덱스를 포함시킨 튜플의 형태가 된다.


>> 실행결과

1
2
3
(0, ('color', 'red'))
(1, ('price', 100))
(2, ('title', 'bread'))
cs



- 튜플의 괄호 없애기


1
2
for i in enumerate(d.items()):
    print(i[0], i[1][0], i[1][1])
cs


>> 실행결과

1
2
3
0 color red
1 price 100
2 title bread
cs



-

1
2
3
4
5
# for i, k, v in enumerate(d.items()):
#     print(i, k, v)
 
for i, (k, v) in enumerate(d.items()):
    print(i, k, v)
cs


>> 1 은 에러 : 하나의 인덱스와 하나의 튜플을 던져주므로 4와 같이 받아야 한다. (튜플의 요소는 2개인 상태)



- 딕셔너리를 통채로 전달해서 키값을 출력하는 방법


1
2
for k in d:
    print(k)
cs


>> 실행결과


1
2
3
color
price
title
cs


>> 이러한 이유로 d.keys() 를 사용하지 않는다.

'Language > Python' 카테고리의 다른 글

<3-4> __name__, 리스트 슬라이싱  (0) 2018.03.08
<3-3> JSON  (0) 2018.03.05
<3-1> 파일 입출력  (0) 2018.02.23
<2-3> 기상청의 전국 날씨정보 파싱, 외부 모듈 추가  (0) 2018.02.22
<2-2> 리스트, 튜플  (0) 2018.02.15