[자료구조와 알고리즘] 딕셔너리(Dictionary) - Python

ByungJik_Oh·2025년 8월 27일

[Algorithms - Python]

목록 보기
3/3
post-thumbnail

📚 딕셔너리(Dictionary)

딕셔너리(Dictionary): 대응관계를 나타내는 자료형으로 key와 value를 한 쌍으로 갖는 구조

  • key: value 형태로 저장되어 {}로 감싼 구조

  • 하나의 딕셔너리 내에서 key는 중복될 수 없음.

dic = {'aaa': 111,
       'bbb': 111,
       'ccc': 222}
print(f'dic: {dic}, 타입: {type(dic)}')
# dic: {'aaa': 111, 'bbb': 111, 'ccc': 222}, 타입: <class 'dict'>

1. key를 이용한 value 접근

  • 리스트와 튜플과 유사하게 key를 사용하여 value에 접근할 수 있다.
dic = {'aaa': 111,
       'bbb': 111,
       'ccc': 222}
print(dic['aaa'], dic['bbb'], dic['ccc'])
# 111 111 222

2. 딕셔너리 데이터 추가

  • 딕셔너리[새로운 key] = value와 같은 형태로 딕셔너리에 데이터를 추가할 수 있다.
dic = {'aaa': 111,
       'bbb': 111,
       'ccc': 222}
       
dic[123] = 'abc'
print(dic)
# {'aaa': 111, 'bbb': 111, 'ccc': 222, 123: 'abc'}

3. 딕셔너리 데이터 삭제

  • 특정 key를 삭제하고 싶다면 pop()함수로 삭제할 수 있으며, 이때 삭제하고자 하는 key를 전달해주면 된다.

  • 이때 pop() 함수는 해당 key를 삭제하고 이에 따른 value를 return한다.

dic = {'aaa': 111,
       'bbb': 111,
       'ccc': 222}

bbb_num = dic.pop('bbb')

print(bbb_num) # 111
print(dic) # {'aaa': 111, 'ccc': 222}

4. 딕셔너리와 관련된 함수

4.1 keys()

  • 딕셔너리에 저장되어 있는 key들을 반환한다.
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}
print(student_info.keys()) # dict_keys(['class', 'name', 'score'])
  • 이때 key들은 dict_keys 자료형으로 반환되고, iterable하다.
  • 그러나 인덱싱은 불가능하다 → 리스트로 변환하여 인덱싱!
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}

for key in student_info.keys():
    print(key)
    # class
    # name
    # score  
 
print(list(student_info.keys())[1]) # name
print(student_info.keys()[1])
# 'dict_keys' object is not subscriptable

4.2 values()

  • 딕셔너리에 저장되어 있는 value들을 반환한다.
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}
print(student_info.values()) # dict_values([3, 'ooo', [75, 50, 100]])
  • 이때 value들은 dict_values 자료형으로 반환되고, iterable하다.
  • 마찬가지로 인덱싱은 불가능하다 → 리스트로 변환하여 인덱싱!
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}

for value in student_info.values():
    print(value)
    # 3
    # ooo
    # [75, 50, 100]   
    
print(list(student_info.values())[1]) # ooo
print(student_info.values()[1])
# 'dict_values' object is not subscriptable

4.3 items()

  • 딕셔너리에 저장되어 있는 key와 value를 한 쌍으로 묶어 튜플로 반환한다.
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}
print(student_info.items())
# dict_items([('class', 3), ('name', 'ooo'), ('score', [75, 50, 100])])
  • 이때 (key, value) 쌍들은 dict_items 자료형으로 반환되고, iterable하다.
  • 마찬가지로 인덱싱은 불가능하다 → 리스트로 변환하여 인덱싱!
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}

for key, value in student_info.items():
    print((key, value))
# ('class', 3)
# ('name', 'ooo')
# ('score', [75, 50, 100])

print(list(student_info.items())[2]) # ('score', [75, 50, 100])
print(student_info.items()[2])
# 'dict_items' object is not subscriptable

4.4 get()

  • key로 딕셔너리의 value에 접근할 때 만약 해당 key값이 없으면 대체할 값을 지정한다.
  • 따로 지정하지 않으면 None을 반환
student_info = {'class': 3,
                'name': 'ooo',
                'score': [75, 50, 100]}

print(student_info.get('class')) # 3 
print(student_info.get('age')) # None
print(student_info.get('age', 'age value 없음')) # age value 없음

profile
精進 "정성을 기울여 노력하고 매진한다"

0개의 댓글