Python/Python기초

Python 8_딕트dict와 set

Codezoy 2019. 11. 27. 13:57

dict: key-value의 쌍으로 이루어진 데이터들을 저장하는
사전(dictionary)식 데이터 타입


     person = {'name': '모쌤', 'age': 16, 'height': 170.5 }
     print(person)
     print(type(person))



출력 결과
{'name': '모쌤', 'age': 16, 'height': 170.5}
<class 'dict'>


     # dict의 데이터 참조 - key 이용
     print(person['name'])
     print(person['age'])


출력 결과
모쌤
16


     # dict의 key를 알아낼 때
     print(person.keys())
     # dict의 value를 알아낼 때
     print(person.values())


출력 결과
dict_keys(['name', 'age', 'height'])
dict_values(['모쌤', 16, 170.5])


     # key와 value를 알아낼 때
     print(person.items())


출력결과
dict_items([('name', '모쌤'), ('age', 16), ('height', 170.5)])

>> 튜플들( ) 로 이루어진 리스트 [ ] 


     students = {1: '강다인', 2: '김수연', 3: '김영광', 10: '안도은'}
     print(students[1])


출력결과
강다인



     # dict에 값을 추가
     students[4] = '김제성'
     print(students)


출력 결과
{1: '강다혜', 2: '김수인', 3: '김영광', 4: '김제성'}


     # dict의 값을 변경 -- 기존의 key 값을 이용
     students[4] = '김길동'
     print(students)


출력 결과
{1: '강다혜', 2: '김수인', 3: '김영광', 4: '김길동'}




     #dict의 값을 삭제 -- pop
     students.pop(4)
     print(students)


출력 결과
{1: '강다혜', 2: '김수인', 3: '김영광'}


     book = {
     'title' : '파이썬 프로그래밍 교과서',
     'authors' : ['제니퍼', '폴', '제이슨'],
     'publisher' : '길벗',
     'isbn' : 97911
     }
     print(book['authors'][0])
     print(book['authors'])


출력결과
제니퍼
['제니퍼', '폴', '제이슨']



set(집합): 저장하는 순서가 중요하지 않고,
            같은 값이 중복 저장되지 않는 데이터 타입


     s1 = {1, 2, 3, 3, 2, 1}
     print(s1)


출력 결과
{1, 2, 3}

순서를 자동으로 정렬해 줌

     s2 = {4, 3, 2}
     print(s2)




     # 집합 연산 : 합집합, 교집합, 차집합
     print(s1 | s2) # 합집합(|)
     print(s1 & s2) # 교집합(&)
     print(s1 - s2) # 차집합(-)

출력 결과
{1, 2, 3, 4}
{2, 3}
{1}


     # 집합에 원소 추가 / 삭제
     s1.add(100) # add(value)
     print(s1)
     s1.remove(3) #remove(value)
     print(s1)


출력 결과
{1, 2, 3, 100}
{1, 2, 100}