tuple_set_dict.py

Jaehyeok·2026년 1월 22일

py.TIL

목록 보기
2/12
post-thumbnail

🟩 tuple

콤마(',')로 구분된 집합 데이터 타입이다.

animals = 'dog', 'cat', 'dog', 'bird', 'shark'
animals
→ ('dog', 'cat', 'dog', 'bird', 'shark')

원소 하나로 구성된 tuple을 만들려면 반드시 원소 뒤에 콤마를 붙여 줘야 한다.

animals = ('dog',)
animals
→ ('dog',)

animals = 'cat', # 괄호가 본질이 아님
animals
→ ('cat',)

인덱스(index)슬라이싱(slicing) 사용 가능하다.

fruits = 'apple', 'banana', 'apple', 'kiwi'

fruits[0]'apple'

fruits[1:3]('banana', 'apple')

tuple은 immutable하다.

fruits[0] = 'mango' # error

tuple은 주로 변경되지 말아야 할 데이터들을 '전달'의 목적으로 사용된다.

Assignment Unpacking

iterable 객체인 tuple에 대입연산자를 사용하여 여러 개의 변수에 대입이 가능하다.
※ iterable 객체: str, list, tuple, set, dict 등 ※

rec = (100, 200)

width, height = rec # 변수들의 tuple에 iterable 객체를 대입
print(width, height)100 200

🟩 set

순서가 존재하지 않으며, 중복값이 없다.
set(iterable) 함수 또는 {}로 만들 수 있다.

animals = {'dog', 'cat', 'dog', 'bird'}
animals
→ {'bird', 'cat', 'dog'} # 순서에 의미 없음

animals = {} # set타입이 아닌 dict타입이 만들어짐

animals = set() # 빈 set가 만들어짐

set의 원소는 hashable 타입만 사용할 수 있다.

animals = set(['a', [1, 2]]) # error: hashable type - list, set, dict 등은 key값 불가

인덱스를 사용할 수 없다.

animals[0] # error

in 연산자는 사용 가능하다.

'bird' in animals
→ True

iterable 객체를 바꿔서 나타낼 수 있다.
※ 원본은 안 바뀜 ※

data = [10,20, 30, 20, 10, 20, 10, 10, 10, 30, 10, 20, 10, 10]

set(data){10, 20, 30}

list({10, 20, 30})[10, 20, 30]

.add() & .remove()

.add() 함수로 원소 추가, .remove() 함수로 삭제할 수 있다.

a = set()

a.add('dog')
a.add('cat')
a
→ {'dog', 'cat'}

a.remove('cat')
a
→ {'dog'}

🟩 dict(딕셔너리)

key-value 쌍으로 저장되는 데이터 집합이다.
※ key-value 쌍을 entry라고 함 ※
※ Python 3.7 부터는 dict 의 key 저장순서로 유지됨, 순회할 때도 저장된 순서대로 리턴 ※

{Key1:Value1, Key2:Value2, Key3:Value3,}

student = {'name':'손오공', 'email':'son@mail.com'}
student
→ {'name': '손오공', 'email': 'son@mail.com'}

len(student) # key-value 쌍의 갯수2

dict는 mutable하다.

student['name'] = '홍길동' # 기존 key값에 대입(수정)
student
→ {'name': '홍길동', 'email': 'son@mail.com'}

student['address'] = '서울시' # 기존에 없던 key값에 대입(새로운 k-v 생성)
student
→ {'name': '홍길동', 'email': 'son@mail.com', 'address': '서울시'}

in 연산자로 key가 존재하는 지 알 수 있다.

'name' in student
→ True

.get()

.get() 함수를 사용하면 예외적인 상황에서도 동작이 가능하다.

student['name'] # 인덱스에 key값을 대입'손오공'
student.get('name')'손오공'

student['age'] # key error
student.get('age') # key값이 없으면 결과값 None

student.get('age', 20) # student.get(key, default) : key 값이 없으면 default 값으로 리턴20

del dict[key]

del dict[key]를 사용하면 key-value 쌍을 삭제할 수 있다.

del student['email']
student
→ {'name': '홍길동', 'address': '서울시'}

dict.update({key:value})

해당 key값을 업데이트 하거나 key값이 없다면 새로 추가할 수 있다.

student.update({'name':'도라에몽'})
student.update({'age':13})
student
→ {'name': '도라에몽', 'address': '서울시', 'age': '13'}

dict()

.dict() 함수로 dict을 생성할 수 있다.

my_dict = {}
my_dict
→ {}
my_dict = dict()
my_dict
→ {}

my_dict = dict(host='127.0.0.1', port='3306')
my_dict
→ {'host': '127.0.0.1', 'port': '3306'}
my_dict = dict([('host', '127.0.0.1'), ('port', '3306')]) # tuple로 dict 생성
my_dict
→ {'host': '127.0.0.1', 'port': '3306'}

key & value 타입

key는 hashable 타입만 가능하다(ex. int, float, str, bool, tuple).
value는 모든 타입이 가능하다.

my_dict = {
    1: 'haha',
    2: 'hoho',
    2: 'hehe', # key는 unique함, 중복된 키를 적으면 마지막 값으로 덮어씌워짐
    # [10, 20]: 32.4 # error: hashable type - list, set, dict 등은 key값 불가
    "two": {
        3.14: 'pi',
        'pi': 3.14
    }, # value값이 dict
    False: [10, 20, 30], # value값이 list
    (1, 2): 'nice' # key값이 tuple
}
my_dict
→ {1: 'haha',
   2: 'hehe',
   'two': {3.14: 'pi', 'pi': 3.14},
   False: [10, 20, 30],
   (1, 2): 'nice'}

my_dict['two']{3.14: 'pi', 'pi': 3.14}
my_dict['two'][3.14]'pi'

my_dict[False][10, 20, 30]
my_dict[False][0]10

my_dict[(1, 2)]'nice'
my_dict[1, 2]'nice'

dict.keys(), dict.values(), dict.items()

student = {
        "name":"최현진",
        "email":"choi@mail.com",
        "age": 23,
        "addr" : "서울"
        }

dict.keys()key로만 구성된 iterable 객체가 리턴된다.

student.keys()
→ dict_keys(['name', 'email', 'age', 'addr'])

dict.values()value로만 구성된 iterable 객체가 리턴된다.

student.values()
→ dict_values(['최현진', 'choi@mail.com', 23, '서울'])

dict.items()는 (key, value) tuple들로 구성된 iterable 객체가 리턴된다.

student.items()
→ dict_items([('name', '최현진'), ('email', 'choi@mail.com'), ('age', 23), ('addr', '서울')])

0개의 댓글