[Python – 기초 강좌] 11. 자료구조 (Data Structure): Dictionary(딕셔너리) 편

앞선 포스팅에서 자료구조의 List, Tuple, Set에 대해 소개했습니다.

오늘은 Python의 다른 중요한 자료구조인 Dictionary(딕셔너리)에 대해 살펴보겠습니다.

List와 Tuple, 그리고 Set에 이어서 Dictionary를 이해하는 것은 Python을 더욱 깊게 이해하고, 데이터를 효율적으로 관리하는 데 큰 도움이 될 것입니다.

이번 포스팅에서는 Dictionary의 정의부터 사용 방법, 그리고 유용한 연산에 이르기까지, Python에서 Set를 어떻게 활용할 수 있는지 자세히 살펴보겠습니다.

Python-Dictionary

Python에서 Dictionary(딕셔너리)란?

Dictionary는 Python의 기본 자료 구조 중 하나로, 키(Key)와 값(Value)의 쌍으로 데이터를 저장합니다.

이는 마치 실제 사전에서 단어와 그 뜻을 연결지어 찾듯, 데이터를 효율적으로 검색하고 관리할 수 있게 해줍니다.

Dictionary의 가장 큰 특징은 데이터에 접근할 때 순서가 아닌, 키(Key)를 사용한다는 것입니다. 이로 인해, 데이터를 빠르게 검색하고 업데이트할 수 있습니다.

또한, Dictionary 내의 키는 유일해야 하며 불변 타입(immutable type)이어야 합니다.

하지만 값(Value)에는 이러한 제한이 없습니다;

값으로는 List나 또 다른 Dictionary를 포함하여 어떠한 타입도 사용할 수 있습니다.

Dictionary 사용 방법

생성

Dictionary를 생성하는 가장 간단한 방법은 중괄호 {}를 사용하고, 콜론 :으로 Key와 Value을 구분하는 것입니다.

또는, dict() 생성자를 사용할 수도 있습니다.

예제

key로 nameage 가 사용되었고, John30이 value로 사용되었습니다.

# create dictionary
my_dict = {'name': 'John', 'age': 30}
print(my_dict)

# create dictionary using dict()
my_dict2 = dict(name='John', age=30)
print(my_dict2)

결과

{'name': 'John', 'age': 30}
{'name': 'John', 'age': 30}

접근

Dictionary의 요소에 접근하기 위해서는 Key를 사용합니다.

Key를 통해 값을 얻거나, get() 메소드를 사용할 수 있습니다.

예제

# access elements
print(my_dict['name'])

# using get() method
print(my_dict.get('age'))

결과

John
30

추가/업데이트/제거

Dictionary에 새로운 Key-Value 쌍(Pair)을 추가하거나, 기존의 값을 업데이트하려면, Key를 사용하여 Value을 할당합니다.

요소를 제거하려면 del 키워드나 pop() 메소드를 사용할 수 있습니다.

예제

my_dict = {'name': 'John', 'age': 30}
print(my_dict)

# add
my_dict['email'] = 'john@example.com'
print(my_dict)

# update
my_dict['name'] = 'Devitworld'

# remove element
del my_dict['age']
print(my_dict)

# pop element
my_dict.pop('email')
print(my_dict)

결과

{'name': 'John', 'age': 30}
{'name': 'John', 'age': 30, 'email': 'john@example.com'}
{'name': 'Devitworld', 'email': 'john@example.com'}
{'name': 'Devitworld'}

찾기

키들의 존재 여부를 확인 할 수 있습니다.

예제

# check if key exists
print('name' in my_dict)

결과

True

그 외 유용한 Dictionary 메소드들

Python Dictionary에는 다양한 내장 메소드가 있어, Dictionary를 효율적으로 사용할 수 있게 해줍니다.

  • keys():
    • 딕셔너리의 키를 모두 얻습니다.
  • values():
    • 딕셔너리의 값들을 모두 얻습니다.
  • items():
    • Key-Value 쌍을 튜플로 얻습니다.
  • update():
    • 다른 Dictionary의 Key-Value pair(쌍)으로 현재 Dictionary를 업데이트합니다.

예제

# Dictionary Methods
my_dict = {'name': 'John', 'age': 30, 'occupation': 'Developer'}

# keys(): get all keys
keys = my_dict.keys()
print("Keys:", keys)

# values(): get all values
values = my_dict.values()
print("Values:", values)

# items(): get all items
items = my_dict.items()
print("Items:", items)

# update(): update dictionary
my_dict.update({'email': 'john@example.com', 'age': 31})
print("Updated Dictionary:", my_dict)

결과

Keys: dict_keys(['name', 'age', 'occupation'])
Values: dict_values(['John', 30, 'Developer'])
Items: dict_items([('name', 'John'), ('age', 30), ('occupation', 'Developer')])
Updated Dictionary: {'name': 'John', 'age': 31, 'occupation': 'Developer', 'email': 'john@example.com'}

참고 문헌

Leave a Comment