본문 바로가기
코딩테스트-파이썬

python 코테관련 기능 정리 -딕셔너리-

by 시니성 2023. 7. 22.

* 딕셔너리는 키 밸류 형태의 파이썬 컬렉션입니다. 형태는 쉽게 설명해 JSON을 떠올리면 됩니다.

딕셔너리 요소들의 기본적인 CRUD 코드는 아래와 같습니다.

# 사전 생성
person = {
    'name': 'Alice',
    'age': 30,
    'city': 'New York'
}

# 사전의 요소에 접근하기
print(person['name'])  # 출력: 'Alice'
print(person['age'])   # 출력: 30
print(person['city'])  # 출력: 'New York'

# 사전의 요소 추가하기
person['gender'] = 'female'
print(person)  # 출력: {'name': 'Alice', 'age': 30, 'city': 'New York', 'gender': 'female'}

# 사전의 요소 수정하기
person['age'] = 31
print(person)  # 출력: {'name': 'Alice', 'age': 31, 'city': 'New York', 'gender': 'female'}

# 사전의 요소 삭제하기
del person['city']
print(person)  # 출력: {'name': 'Alice', 'age': 31, 'gender': 'female'}

 

* zip() 함수는 여러 개의 iterable(반복 가능한) 객체를 묶어서 하나의 iterator(반복자)로 만드는 파이썬 내장 함수입니다. 각 iterable 객체들에서 같은 위치에 있는 요소들을 튜플 형태로 묶어서 iterator로 반환합니다. 만약 인자로 전달된 iterable 객체들의 길이가 다르면, 가장 짧은 iterable의 길이에 맞춰서 묶습니다.

튜플 형태로 묶인 자료를 key - value 쌍으로 바꾸어 딕셔너리를 생성할 수 있습니다.

# 두 개의 iterable 객체
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']

# zip을 사용하여 두 iterable을 묶음
zipped = zip(keys, values)

# 딕셔너리로 변환
my_dict = dict(zipped)
print(my_dict)
# 출력: {'name': 'Alice', 'age': 30, 'city': 'New York'}

* dict1.update(dict2)

딕셔너리 병합에 사용됩니다.

dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}

dict1.update(dict2)

print(dict1)  # 출력: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
728x90