Skip to content

딕셔너리(Dictionary)

선언과 구조

딕셔너리는 중괄호 ({})를 사용하여 key-value 쌍으로 데이터를 저장하는 자료형이다. 기본 구조는 다음과 같다.

python
{
    key1: value1,
    key2: value2,
    key3: value3,
    ...
}

key 값은 고유해야 하며, value 값은 중복될 수 있다. 또 value 값은 단일 값 뿐만 아니라 리스트, 튜플, 딕셔너리 등 다양한 자료형을 가질 수 있다. 딕셔너리는 가변(mutable) 자료형으로, 요소를 추가하거나 삭제할 수 있다.

딕셔너리를 선언하는 방법은 다음과 같다.

python
d1 = {}
d2 = { "name": "홍길동", "email": "test1@abc.com", "phone": "010-1234-5678" }
d3 = dict(name="홍길동", email="test2@abc.com", phone="010-8765-4321")
print(type(d1), type(d2), type(d3))
plaintext
<class 'dict'> <class 'dict'> <class 'dict'>

원소 추가 / 수정 / 삭제

딕셔너리에 원소를 추가하는 방법은 다음과 같다.

python
fruits = { "a": "apple", "b": "banana" }
fruits["c"] = "carot"
print(fruits)
plaintext
{'a': 'apple', 'b': 'banana', 'c': 'carot'}

기존 키 값이 존재하면 값을 다음과 같이 수정할 수 있다.

python
fruits = { "a": "apple", "b": "banana" }
fruits["b"] = "blueberry"
print(fruits)
plaintext
{'a': 'apple', 'b': 'blueberry'}

딕셔너리의 값은 리스트를 포함할 수 있으며, 리스트의 원소를 추가하거나 수정할 수 있다.

python
fruits = { "a": "apple", "b": "banana" }
fruits["c"] = ["coconut", "cherry"]
print(fruits)
plaintext
{'a': 'apple', 'b': 'banana', 'c': ['coconut', 'cherry']}

딕셔너리에서 원소를 삭제하는 방법은 다음과 같다.

python
fruits = { "a": "apple", "b": "banana", "c": ["coconut", "cherry"] }
del fruits["c"]
print(fruits)
plaintext
{'a': 'apple', 'b': 'banana'}

만약 딕셔너리에 존재하지 않는 키를 삭제하려고 하면 KeyError가 발생한다.

python
del fruits["d"] 

키 값에 d가 존재하지 않으므로 KeyError가 발생한다.

딕셔너리의 모든 원소를 삭제하려면 clear() 메서드를 사용할 수 있다.

python
fruits = { "a": "apple", "b": "banana", "c": ["coconut", "cherry"] }
fruits.clear()
print(fruits)
plaintext
{}

딕셔너리의 키(key)와 값(value)을 삭제한 것이다. 딕셔너리 전체를 삭제하려면 del 연산자를 사용한다.

python
del fruits

탐색

딕셔너리는 index()를 사용하지 않는다. 딕셔너리에서 key 값을 기준으로 탐색을 할 때는 in 연산자를 사용한다.

python
fruits = { "a": "apple", "b": "banana", "c": ["coconut", "cherry"] }
print("b" in fruits)
print("banana" in fruits)
plaintext
True
False

value 값을 기준으로 탐색할 때는 values() 또는 items() 메서드를 사용한다.

python
fruits = { "a": "apple", "b": "banana", "c": "cherry" }
print(fruits.keys(), type(fruits.keys()))
print(fruits.values(), type(fruits.values()))
print(fruits.items(), type(fruits.items()))
plaintext
dict_keys(['a', 'b', 'c']) <class 'dict_keys'>
dict_values(['apple', 'banana', 'cherry']) <class 'dict_values'>
dict_items([('a', 'apple'), ('b', 'banana'), ('c', 'cherry')]) <class 'dict_items'>

딕셔너리 value 값 중에 banana가 있는지 탐색해보자.

확인하기
python
fruits = { "a": "apple", "b": "banana", "c": "cherry" }
print("banana" in fruits.values()) # in 연산자를 사용하여 value 값 탐색
for k, v in fruits.items():        # items() 메서드를 사용하여 key-value 쌍 탐색
    if v == "banana":
        print(k, v)
plaintext
True
b banana

병합

두 개의 딕셔너리를 병합할 때는 update() 메서드를 사용하거나, | 연산자를 사용할 수 있다. value 값이 중복되는 경우, 마지막에 있는 값으로 덮어쓰게 된다.

python
f1 = { "a": "apple", "b": "banana" }
f2 = { "b": "blueberry", "c": "coconut" }
f1.update(f2)
f3 = f1 | f2
print(f1)
print(f3)
plaintext
{'a': 'apple', 'b': 'blueberry', 'c': 'coconut'}
{'a': 'apple', 'b': 'blueberry', 'c': 'coconut'}

정렬

key 값을 기준으로 정렬

python
data = { "d": 8, "c": 5, "a": 9, "b": 2 }
d1 = sorted(data)
d2 = sorted(data.keys())
d3 = sorted(data.keys(), reverse=True)
print(d1, d2, d3)
plaintext
['a', 'b', 'c', 'd'] ['a', 'b', 'c', 'd'] ['d', 'c', 'b', 'a']

내림차순으로 정렬하기 위해서는 reverse 인자의 값을 True로 설정한다.

value 값을 기준으로 정렬

python
data = { "d": 8, "c": 5, "a": 9, "b": 2 }
d2 = sorted(data.values())
d3 = sorted(data.values(), reverse=True)
print(d2, d3)
plaintext
[2, 5, 8, 9] [9, 8, 5, 2]

key-value 쌍을 기준으로 정렬

python
data = { "d": 8, "c": 5, "a": 9, "b": 2 }
d1 = sorted(data.items())
d2 = sorted(data.items(), reverse=True)
print(d1, d2, sep="\n")
plaintext
[('a', 9), ('b', 2), ('c', 5), ('d', 8)]
[('d', 8), ('c', 5), ('b', 2), ('a', 9)]

λ-식을 사용한 정렬

python
data = { "d": 8, "c": 5, "a": 9, "b": 2 }
# key 값을 기준으로 정렬
k1 = sorted(data.items(), key=lambda x: x[0])               # 오름차순
k2 = sorted(data.items(), key=lambda x: x[0], reverse=True) # 내림차순

# value 값을 기준으로 정렬
v1 = sorted(data.items(), key=lambda x: x[1])               # 오름차순
v2 = sorted(data.items(), key=lambda x: x[1], reverse=True) # 내림차순
print(k1, k2, v1, v2, sep="\n")
plaintext
[('a', 9), ('b', 2), ('c', 5), ('d', 8)]
[('d', 8), ('c', 5), ('b', 2), ('a', 9)]
[('b', 2), ('c', 5), ('d', 8), ('a', 9)]
[('a', 9), ('d', 8), ('c', 5), ('b', 2)]

value 값이 가장 큰 key 값을 찾으려면 다음과 같이 할 수 있다.

python
data = { "d": 8, "c": 5, "a": 9, "b": 2 }
sorted_data = sorted(data.items(), key=lambda x: x[1])
print(sorted_data[-1], sorted_data[-1][0], sorted_data[-1][1])
plaintext
[('a', 9), 'a', 9]

딕셔너리 datavalue 값을 기준으로 오름차순 정렬한 후, 마지막 원소를 가져온다. sorted_data[-1]('a', 9)이고, key 값은 sorted_data[-1][0], value 값은 sorted_data[-1][1]로 표현할 수 있다.

Powered by vitepress-logo-mini