자동화를 위한 Python 공부 6일차
dictionary type : dict
사람은 누구든지 "이름" = "홍길동", "생일" = "몇 월 며칠" 등으로 구별할 수 있다. 파이썬은 영리하게도 이러한 대응 관계를 나타낼 수 있는 자료형을 가지고 있다. 요즘 사용하는 대부분의 언어도 이러한 대응 관계를 나타내는 자료형을 갖고 있는데, 이를 연관 배열(Associative array) 또는 해시(Hash)라고 한다.
파이썬에서는 이러한 자료형을 딕셔너리(Dictionary)라고 하는데, 단어 그대로 해석하면 사전이라는 뜻이다. 즉 "people"이라는 단어에 "사람", "baseball"이라는 단어에 "야구"라는 뜻이 부합되듯이 딕셔너리는 Key와 Value를 한 쌍으로 갖는 자료형이다. 예컨대 Key가 "baseball"이라면 Value는 "야구"가 될 것이다.
딕셔너리는 리스트나 튜플처럼 순차적으로(sequential) 해당 요솟값을 구하지 않고 Key를 통해 Value를 얻는다. 이것이 바로 딕셔너리의 가장 큰 특징이다. baseball이라는 단어의 뜻을 찾기 위해 사전의 내용을 순차적으로 모두 검색하는 것이 아니라 baseball이라는 단어가 있는 곳만 펼쳐 보는 것이다.
[출처] - https://wikidocs.net/book/1
점프 투 파이썬
** 점프 투 파이썬 오프라인 책(개정판) 출간 !! (2019.06) ** * [책 구입 안내](https://wikidocs.net/4321) 이 책은 파이썬 ...
wikidocs.net
- dict 에 저장되는 값은 항상 key:value 형식으로 저장하며 , key = immutable 하며 value = mutalble 하다.
- key는 절대 중복을 허용하지 않으며 , 항상 하나의 key만 존재한다, 반면 value는 어떤 형태의 값이라도 저장이 가능하다.
- dict는 index가 존재하지 않으므로 순서가 없다 , 이는 tuple이나 list와는 다른점이다.
dict 생성
#dic 생성
d1 = {}
print(f'd1\'s type : {type(d1)}')
d2 = dict(name = 'moon' , age = '30' , sex = 'male')
print(f'd2\'s type : {type(d2)} , d2 = {d2}')
list = [[ 'name','moon kwang hoon'],['age','30'],['sex','male']]
d3 = dict(list)
print(f'd3 is {d3}')
>>>
d1's type : <class 'dict'>
d2's type : <class 'dict'> , d2 = {'name': 'moon', 'age': '30', 'sex': 'male'}
d3 is {'name': 'moon kwang hoon', 'age': '30', 'sex': 'male'}
dict 자료형 공통 연산
#dict에서의 자료형 공통 연산
print(d3['name']) #dict 는 key:value 타입이라 key 로 연산
print(d3['name']+d3['age'])
d3['email'] = 'glq032@naver.com'
print(d3)
print(d3['email'])
>>>
moon kwang hoon
moon kwang hoon30
{'name': 'moon kwang hoon', 'age': '30', 'sex': 'male', 'email': 'glq032@naver.com'}
glq032@naver.com
#dic method 1. get
d3.get('address','No')
result = d3.get( 'age', False ) #검색할 인자와 , 없을시 반환값
if result:
print( f'age : {result}' )
else:
print( f'age key는 존재하지 않음' )
>>>
age : 30
#dict method 2. update
d4 = [['name','james'],[ 'hobby','soccer'],['nationality','U.S.A'],['phone','007']]
d3.update(d4) # name 은 수정 , 나머지는 추가 -> update
print('d3 is', d3)
>>>
d3 is {'name': 'james', 'age': '30', 'sex': 'male', 'email': 'glq032@naver.com', 'hobby': 'soccer', 'nationality': 'U.S.A', 'phone': '007'}
#del 명령
del d3['email']
print('d3 is', d3)
>>>
d3 is {'name': 'james', 'age': '30', 'sex': 'male', 'hobby': 'soccer', 'nationality': 'U.S.A', 'phone': '007'}
#pop & listpop
print(f' d3.pop("age") = {d3.pop("age")}')
print(f' d3.popitem() = {d3.popitem()} \n d3 = {d3}') # 마지막 요소를 출력후 지워버림
list_pop = [1,2,3,4,5,6]
print(f'list_pop = {list_pop}')
print(f'list_pop.pop() = {list_pop.pop()}')
print(f'pop()을 거친 list_pop = {list_pop}')
print(f'list_pop.clear() = {list_pop.clear()}')
>>>
d3.pop("age") = 30
d3.popitem() = ('phone', '007')
d3 = {'name': 'james', 'sex': 'male', 'hobby': 'soccer', 'nationality': 'U.S.A'}
dict 의 순회
#순회 1
list = [[ 'name','moon kwang hoon'],['age','30'],['sex','male']]
for i in list:
print(i)
for i , j in list:
print(f' {i} : {j}')
>>>
['name', 'moon kwang hoon']
['age', '30']
['sex', 'male']
name : moon kwang hoon
age : 30
sex : male
d = { 'hong': [ 50, 50, 50, 150, 50.0 ],
'kim': [ 90, 90, 90, 270, 90.0 ],
'lee': [ 70, 70, 70, 210, 70.0 ] }
for key, value in d.items():
print( f'{key:<5}', end = '' )
for v in value:
print( f'{v} ', end = '' )
print()
>>>
hong 50 50 50 150 50.0
kim 90 90 90 270 90.0
lee 70 70 70 210 70.0
dict comprehension
dict 변수 = [ key:value for dict에 저장할 값 in 반복식 ]
dict 변수 = [ key:value for dict에 저장할 값 in 반복식 if 조건식]
# dict comprehension 적용하지 않는 경우
# 문자 빈도수 저장 dict 생성
word = 'letters'
d = {}
for i in word:
d[ i ] = word.count( i ) #문자 빈도수를 체크하는 코드
print( f'd : {d} ( {len( d )} )' )
>>>
d : {'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1} ( 5 )
# dict comprehension 적용
d = { letter:word.count( letter ) for letter in word }
print( f'd : {d} ( {len( d )} )' )
>>>
d : {'l': 1, 'e': 2, 't': 2, 'r': 1, 's': 1} ( 5 )
'Python & Automation' 카테고리의 다른 글
[Ansible] Control node & Managed node 설치 및 ssh 접속 (0) | 2022.02.15 |
---|---|
[Ansible] 환경 구성 자동화를 위한 Ansible (0) | 2022.02.14 |
Python Strudy - day 5 (0) | 2022.01.31 |
Python Study - day 4 (0) | 2022.01.27 |
Python Study - day 3 (0) | 2022.01.27 |