Dictionary(Dict)는 key-value
형태의 데이터를 갖고 있는 Collection입니다.
다른 언어에서는 Map이라고 하지만, Python은 Dictionary라고 합니다.
이 글에서는 Dict를 사용하는 방법에 대해서 알아보겠습니다.
1. 딕셔너리 정의
Dictionary(dict)를 정의하려면 다음과 같이 { }
안에 key-value
형태의 데이터를 입력하면 됩니다.
cities = {
'Korea': 'Seoul',
'Japan': 'Tokyo',
"China": 'Beijing',
'USA': 'Washington',
'France': 'Paris'
}
만약 데이터가 없는 dict를 정의하고 싶다면 { }
으로 데이터를 정의하지 않으면 됩니다.
cities = {}
2. 딕셔너리의 데이터 접근
dict의 데이터를 접근하려면 다음과 같이 dict['key']
또는 dict.get('key')
로 접근하면 됩니다.
cities = {
'Korea': 'Seoul',
'Japan': 'Tokyo',
"China": 'Beijing',
'USA': 'Washington',
'France': 'Paris'
}
print(cities)
print(cities['Korea'])
print(cities.get('Japan'))
Output:
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington', 'France': 'Paris'}
Seoul
Tokyo
3. 딕셔너리의 데이터 변경
데이터를 변경하려면 다음과 같이 할 수 있습니다.
cities['France'] = 'PARIS'
print(cities['France'])
Output:
PARIS
4. 딕셔너리에 데이터 추가
데이터를 추가하는 것도 데이터를 변경하는 것과 동일합니다. 다른점은 존재하지 않는 key에 대해서 value를 설정하는 것입니다.
cities['Germany'] = 'Berlin'
print(cities)
Output:
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington', 'France': 'Paris', 'Germany': 'Berlin'}
5. 딕셔너리의 데이터 삭제
pop(key)
로 데이터를 제거할 수 있습니다.
cities = {
'Korea': 'Seoul',
'Japan': 'Tokyo',
"China": 'Beijing',
'USA': 'Washington',
'France': 'Paris'
}
removed = cities.pop('France')
print(removed)
print(cities)
Output:
Paris
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington'}
popitem
popitem
은 가장 마지막에 추가된 아이템을 제거합니다. (python 3.7 이전 버전은 random으로 아이템을 삭제합니다)
removed = cities.popitem()
print(removed)
print(cities)
Output:
('France', 'Paris')
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington'}
del
del
으로 아이템을 삭제할 수도 있습니다.
del cities['USA']
print(cities)
Output:
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'France': 'Paris'}
다음과 같이 dict 객체를 모두 삭제할 수 있습니다. 삭제한 이후에 dict 객체는 존재하지 않기 때문에 접근하면 에러가 발생합니다.
del cities
clear
clear()
는 dict에 추가된 모든 데이터를 제거합니다. dict 객체는 삭제되지 않고 비어있는 상태로 남아있습니다.
cities.clear()
print(cities)
6. 반복문으로 딕셔너리의 데이터 순회
다음과 같이 for in
으로 모든 아이템을 순회할 수 있습니다.
for country in cities:
print(country)
Output:
Korea
Japan
China
USA
France
value를 출력하고 싶다면 다음과 같이 하면 됩니다.
for country in cities.values():
print(country)
Output:
Seoul
Tokyo
Beijing
Washington
Paris
key와 value를 모두 순회하고 싶다면 다음과 같이 하면 됩니다.
for country, city in cities.items():
print('country: {}, city: {}'.format(country, city))
Output:
country: Korea, city: Seoul
country: Japan, city: Tokyo
country: China, city: Beijing
country: USA, city: Washington
country: France, city: Paris
7. 딕셔너리의 Key 존재 확인
다음과 같이 in
을 사용하여 dict에 어떤 key가 존재하는지 확인할 수 있습니다.
if "China" in cities:
print("China is in the cities")
if "Thailand" not in cities:
print("Thailand is not in the cities")
Output:
China is in the cities
Thailand is not in the cities
8. 딕셔너리의 길이 확인
len()
으로 dict의 길이를 계산할 수 있습니다.
print(len(cities))
9. 딕셔너리의 객체 복사
다음과 같이 copy()
를 이용하여 dict 객체를 복사할 수 있습니다.
cities = {
'Korea': 'Seoul',
'Japan': 'Tokyo',
"China": 'Beijing',
'USA': 'Washington',
'France': 'Paris'
}
copied = cities.copy()
copied['Germany'] = 'Berlin'
print(cities)
print(copied)
Output:
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington', 'France': 'Paris'}
{'Korea': 'Seoul', 'Japan': 'Tokyo', 'China': 'Beijing', 'USA': 'Washington', 'France': 'Paris', 'Germany': 'Berlin'}
또는, dict()
를 이용하여 객체를 복사할 수 있습니다.
copied = dict(cities)
copied['Germany'] = 'Berlin'
print(cities)
print(copied)
Related Posts
- Python 소수점 반올림, round() 예제
- 파이썬 주석 처리, 단축키 소개
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 정리 및 예제
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 디폴트 매개변수(Default parameters)
- Python - filter() 사용 방법 및 예제