딕셔너리 (Dictionary)
파이썬은 다양한 데이터 구조를 제공하여 개발자가 데이터를 효율적으로 조작할 수 있도록 도와줍니다.
이 중에서도 딕셔너리(Dictionary)는 매우 유용한 자료형 중 하나입니다.
딕셔너리는 키(key)와 값(value)의 쌍으로 데이터를 저장하는 자료구조로, 데이터를 검색하고 조작하는 데 매우 효과적입니다.
이번 블로그에서는 파이썬의 딕셔너리에 대해 자세히 알아보도록 하겠습니다.
1. 딕셔너리의 개념과 특징
딕셔너리는 중괄호({})로 묶여 있으며, 키와 값은 콜론(:)으로 구분됩니다.
키는 고유한 값이어야 하고, 값은 중복되어도 상관 없습니다.
딕셔너리는 가변적인(mutable) 자료형이므로 내부 데이터를 추가, 수정, 삭제할 수 있습니다.
2. 딕셔너리 생성하기
딕셔너리를 생성하는 가장 간단한 방법은 중괄호({})를 사용하는 것입니다.
예를 들어, 다음과 같이 딕셔너리를 생성할 수 있습니다.
my_dict = {'apple': 1, 'banana': 2, 'orange': 3}
my_dict
# {'apple': 1, 'banana': 2, 'orange': 3}
3. 딕셔너리 값에 접근하기
딕셔너리의 값에 접근하기 위해서는 해당 키를 사용합니다.
예를 들어, 위에서 생성한 `my_dict` 딕셔너리에서 "apple"의 값을 얻으려면 다음과 같이 할 수 있습니다.
value = my_dict["apple"]
print(value)
# 1
4. 딕셔너리 값 추가, 수정, 삭제하기
딕셔너리에 새로운 값을 추가하거나 기존 값을 수정하려면 키를 사용합니다.
예를 들어, 다음과 같이 할 수 있습니다.
4 - 1. 값 추가하기
my_dict["grape"] = 4
4 - 2. 값 수정하기
my_dict["banana"] = 5
4 - 3. 값 삭제하기
del my_dict["orange"]
5. 딕셔너리 순회하기
딕셔너리의 모든 키와 값에 접근하기 위해서는 반복문을 사용할 수 있습니다.
예를 들어, 다음과 같이 할 수 있습니다.
for key, value in my_dict.items():
print(key, value)
6. 딕셔너리 메서드
파이썬은 딕셔너리를 다루기 위한 다양한 메서드를 제공합니다.
몇 가지 유용한 메서드는 다음과 같습니다.
- `keys()`
- 딕셔너리의 모든 키를 반환합니다.
- `values()`
- 딕셔너리의 모든 값들을 반환합니다.
- `item()`
- 딕셔너리의 모든 키와 값 쌍을 반환합니다.
- `get(key)`
- 주어진 키의 값을 반환합니다. 키가 없을 경우 None을 반환합니다.
딕셔너리의 사용은 데이터를 효율적으로 저장하고 검색하는 데 매우 유용합니다.
딕셔너리를 적절히 활용하여 파이썬 프로그래밍을 더욱 효과적으로 수행할 수 있습니다.
잘못된 정보는 댓글로 알려주시면 감사하겠습니다.
'Python' 카테고리의 다른 글
Python - 14. 파이썬의 1급 객체(First-Class Object) (0) | 2023.07.16 |
---|---|
Python - 13. 파이썬의 함수(Function)과 인수(argument). (0) | 2023.07.15 |
Python - 11. 파이썬의 집합(Set) (0) | 2023.07.13 |
Python - 10. 파이썬에서 2차원 리스트/튜플 활용하기 (0) | 2023.07.12 |
Python - 9. 파이썬 튜플(tuple), 불변한(Immutable)한 자료구조. (0) | 2023.07.11 |