
✅ 딕셔너리(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'>
dic = {'aaa': 111,
'bbb': 111,
'ccc': 222}
print(dic['aaa'], dic['bbb'], dic['ccc'])
# 111 111 222
dic = {'aaa': 111,
'bbb': 111,
'ccc': 222}
dic[123] = 'abc'
print(dic)
# {'aaa': 111, 'bbb': 111, 'ccc': 222, 123: 'abc'}
특정 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}
student_info = {'class': 3,
'name': 'ooo',
'score': [75, 50, 100]}
print(student_info.keys()) # dict_keys(['class', 'name', 'score'])
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
student_info = {'class': 3,
'name': 'ooo',
'score': [75, 50, 100]}
print(student_info.values()) # dict_values([3, 'ooo', [75, 50, 100]])
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
student_info = {'class': 3,
'name': 'ooo',
'score': [75, 50, 100]}
print(student_info.items())
# dict_items([('class', 3), ('name', 'ooo'), ('score', [75, 50, 100])])
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
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 없음