Python

Python(9) 튜플, 딕셔너리, Set(집합)

UserDonghu 2023. 9. 13. 19:56

튜플

튜플은 안에 있는 값이 변경 불가능한 자료형이 아님

참조 불변임

리스트에 비해 처리속도가 조금 더 빠름

x = (1, 2, 3)
# x[0] = 1000 Error

x = [10, 20, 30]
y = (1, 2, x)
x[0] = 1000
print(y) # (1, 2, [1000, 20, 30])

 

데이터의 변경이 민감하고, 참조의 개수가 변하면 안될 때 사용

s = {'one':1, 'two':2}
print(s.items()) # dict_items([('one', 1), ('two', 2)]) 배열 안 튜플 형태로 반환

 

# 튜플 덧셈
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
tuple3 = tuple1 + tuple2
print(tuple3) # (1, 2, 3, 4, 5, 6)

# 튜플 슬라이싱
t = (1, 2, 3, 4, 5)
print(t[0]) # 1
print(t[:3]) # (1, 2, 3)

# 튜플 메서드
t = (1, 1, 1, 2, 3, 4)
print(t.count(1)) # 3
print(t.index(3)) # 4

 

딕셔너리

파이썬 3.6 버전 부터 삽입 순서가 보장

 

딕셔너리 생성

d = {'bb': 100, 'hello': 10, 'world': 20, 'aa': 30}
print(d) # {'bb': 100, 'hello': 10, 'world': 20, 'aa': 30}

d = dict([('one' , '하나'), ('two', '둘')])
print(d) # {'one': '하나', 'two': '둘'};

d = dict([['one' , '하나'], ['two', '둘']])
print(d) # {'one': '하나', 'two': '둘'}

d = dict(name='licat', age=10)
print(d) # {'name': 'licat', 'age': '10}

 

딕셔너리 안에는 다양하게 넣을 수 있음

complex_dict = {
    "numbers": [1, 2, 3],
    42: "answer",
    ("x", "y"): [10, 20],
    True: [100, 200]
}
print(complex_dict["numbers"])  # [1, 2, 3]
print(complex_dict[42])         # answer
print(complex_dict[("x", "y")]) # [10, 20]
print(complex_dict[True]) # [100, 200]

 

딕셔너리 value 변경/추가하기

person = {'name': 'licat', 'city': 'Jeju'}
person['name'] = 'mura'
person['city'] = 'Seoul'

print(person) # {'name': 'mura', 'city', 'Seoul'}

person['age'] = 19 # 없으면 추가
print(person) # {'name': 'mura', 'city', 'Seoul', 'age': 19}

 

딕셔너리 메서드

copy : 얕은 복사

hero = {'name': 'licat', 'age': 10}
hero2 = hero
hero2['name'] = 'mura'
print(hero, hero2) # {'name': 'mura', 'age': 10} {'name': 'mura', 'age': 10}

hero = {'name': 'licat', 'age': 10}
hero2 = hero.copy()
hero2['name'] = 'mura'
print(hero, hero2) # {'name': 'licat', 'age': 10} {'name': 'mura', 'age': 10}

 

items : 요소들을 반환

hero = {'name': 'licat', 'age': 10}
print(hero.items()) # dict_items([('name', 'licat'), ('age', 10)])
print(type(hero.items())) # <class 'dict_items'>
print(list(hero.items())[0]) # ('name', 'licat')

 

 

keys : 키 값들을 반환

hero = {'name': 'licat', 'age': 10}
print(hero.keys()) # dict_keys(['name', 'age'])
print(type(hero.keys())) # <class 'dict_keys'>

for i in hero.keys():
    print(i)
    
# name
# age

 

values : 밸류 값 들을 반환

hero = {'name': 'licat', 'age': 10}
print(hero.values()) # dict_values(['licat', 10])
print(type(hero.values())) # <class 'dict_values'>

'licat' in hero # False 키값으로만 in 가능
'licat' in hero.values() # True 이렇게 써야함

 

fromkeys

keys = ['name', 'city', 'job']
values = None
print(dict.fromkeys(keys, values)) # {'name': None, 'city': None, 'job': None}

 

get : value가져오기

d = {'name': 'licat', 'city': 'Jeju'}
print(d['name'])
print(d.get('name')) # 기억하고 있어야함

# print(d['age']) # Error 없는값이라 에러남
print(d.get('age', '값 없음!')) # 값 없음! 출력

 

pop : 꺼내고 반환

numbers = {'one': '하나', 'two': '둘', 'three': '셋'}
one_value = numbers.pop('one')
print(one_value) # 하나
print(numbers) # {'two': '둘', 'three': '셋'}

numbers.pop() # Error 딕셔너리에서는 인자 필요

 

popitem : 마지막 요소 꺼내고 반환

numbers = {'one': '하나', 'two': '둘', 'three': '셋'}
item = numbers.popitem()
print(item) # 셋
print(numbers) # {'one': '하나', 'two': '둘'}

 

setdefault : 키가 없으면 추가

numbers = {'one': '하나', 'two': '둘', 'three': '셋'}
four_value = numbers.setdefault("four", "넷") # 키가 없으면 넣고
print(four_value) # 넷
print(numbers) # {'one': '하나', 'two': '둘', 'three': '셋', 'four': '넷'}

three_value = numbers.setdefault("three", '3') # 있으면 안넣음
print(three_value) # 셋
print(numbers) # {'one': '하나', 'two': '둘', 'three': '셋', 'four': '넷'}

 

update : 키가 없으면 넣고 있으면 바꿈

numbers = {'one': '하나', 'two': '둘', 'three': '셋'}
numbers.update({'four': '넷', 'five': '다섯'}) # 값이 있든 없든 넣음
print(numbers) # {'one': '하나', 'two': '둘', 'three': '셋', 'four': '넷', 'five': '다섯'}

numbers.update({'three': '3'}) # 있으면 바꿈
print(numbers) # {'one': '하나', 'two': '둘', 'three': '3', 'four': '넷', 'five': '다섯'}

 

연습문제

국영수 = {'국어': 97, '영어': 38, '수학': 90}
# 문제1: 다음 국영수 dict의 점수 평균을 구하는 코드를 작성하세요.
print(sum(국영수.values())/len(국영수))

# 문제2: {'사회': 70, '과학': 85}가 추가되었습니다. dict의 평균을 구하는 코드를 작성하세요.
국영수.update({'사회': 70, '과학': 85})
print(sum(국영수.values())/len(국영수))

# 문제3: 영어와 수학점수가 각각 10점씩 올랐습니다. 점수를 추가하는 코드를 작성하세요.
국영수.update({'영어': 국영수.get('영어')+10, '수학': 국영수.get('수학')+10})
print(국영수)

# 문제4: 최종 점수에서 가장 높은 점수를 출력하는 코드를 작성하세요.
print(max(국영수.values()))

# 문제5: 가장 높은 점수인 과목을 출력해주세요.
print(max(국영수.items(), key=lambda x:x[1])[0])

print(max(국영수, key=국영수.get)) # 제일 깔끔

values = list(국영수.values())
print(list(국영수.keys())[values.index(max(values))])

print(sorted(국영수.items(), key=lambda x:x[1], reverse=True)[0][0])

 

Set(집합)

중복 되지 않음

순서가 없음

교집합, 차집합, 합집합 등이 가능

print(set('hello'))

s = {'licat', 'licat', 'mura', 'binky'}
print(len(s)) # 3 중복 제외

 

# 주의
t = {} # dict
t = () # tuple
t = tuple() # 빈 튜플
t = (0) # int
t = (0,) # tuple
t = {0} # set
t = set() # 빈 집합

 

합집합

s = {1, 1, 1, 2, 3, 4, 4, 4}
ss = {4, 5, 6}

print(s | ss) # {1, 2, 3, 4, 5, 6}

 

교집합

s = {1, 1, 1, 2, 3, 4, 4, 4}
ss = {4, 5, 6}

print(s & ss) # {4}

 

차집합

s = {1, 1, 1, 2, 3, 4, 4, 4}
ss = {4, 5, 6}

print(s - ss) # {1, 2, 3}

 

집합 메서드

# add
s = {1, 1, 1, 2, 3, 4, 4, 4}
s.add(100)
print(s) # {1, 2, 3, 4, 100}

# remove
s.remove(1000) # Error 있는 값만 remove
s. discard(100) # 없는 값으로 해도 에러 안남

'Python' 카테고리의 다른 글

Python(11) if, match, for, while 문  (0) 2023.09.15
Python(10) 리스트 컴프리헨션, 삼항 연산자  (0) 2023.09.13
Python(8) 리스트  (0) 2023.09.12
Python(7) 함수  (0) 2023.09.12
Python(6) 연산  (0) 2023.09.11