1. key, value 불러오기
1.1. get
get()은 key를 통해 value를 가져올 수 있습니다.
만약 존재하지 않는 key를 입력하면 'None'을 반환합니다.
testDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 6:'f'}
print(testDict.get('d')) # 4
print(testDict.get('6')) # None
print(testDict.get(6)) # f
1.2. pop, popitem
pop()은 key를 이용해 value를 꺼내면서 해당 값을 삭제합니다. 만약 없는 key를 입력하면 KeyError가 발생합니다.
testDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 6:'f'}
print(testDict.pop(6))
print(testDict) # {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
print(testDict.pop(6)) # KeyError:6
popitem()은 마지막 item을 가져오고 동시에 제거합니다. 리스트의 pop()과 같은 역할을 합니다.
testDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 6:'f'}
print(testDict.popitem())
print(testDict)
# (6, 'f')
# {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
print(testDict.popitem())
print(testDict)
# ('e', 5)
# {'a': 1, 'b': 2, 'c': 3, 'd': 4}
2. key, value 추가 및 변경
2.1. fromkeys (딕셔너리 객체 생성)
fromkeys()는 key값을 리스트로 입력하면 두 번째 인자의 값을 value로 쌍으로 저장합니다.
value를 지정하지 않으면 'None'로 저장됩니다.
testDict = dict.fromkeys(['a', 'b', 5, 6], 10)
print(testDict)
# {'a': 10, 'b': 10, 5: 10, 6: 10}
testDict = dict.fromkeys(['a', 'b', 5, 6])
print(testDict)
# {'a': None, 'b': None, 5: None, 6: None}
2.2. setdefault, update
setdefault()는 key, value 쌍을 추가하는 메소드입니다. 만약 이미 존재하는 key를 입력하면 값을 추가하거나 변경하지 않습니다.
testDict = {'a': 10, 'b': 10}
testDict.setdefault('a', 'setdefaultA')
print(testDict)
# {'a': 10, 'b': 10}
testDict.setdefault('c', 'setdefaultC')
print(testDict)
# {'a': 10, 'b': 10, 'c': 'setdefaultC'}
update()는 여러가지 인자로 값을 갱신할 수 있습니다.
testDict = {'a': 10, 'b': 10}
testDict.update(a='updateA')
testDict.update(b='updateB', c='updateC')
print(testDict)
# {'a': 'updateA', 'b': 'updateB', 'c': 'updateC'}
위 예제는 key가 문자열인 경우에만 사용 가능합니다. 따옴표를 붙이지 않고 '=' 뒤에 변경할 value를 입력합니다. 이때 존재하지 않는 key를 입력하면 새로 쌍을 추가합니다.
testDict.update({'a':'updateA', 'b':'updateB', 10:'updateC'})
print(testDict)
# {'a': 'updateA', 'b': 'updateB', 10: 'updateC'}
중괄호'{}'를 사용하면 객체 생성과 같은 방법으로 값을 추가 및 갱신할 수 있습니다.
testDict.update([['a', 'updateA'],[30, 10]])
print(testDict)
# {'a': 'updateA', 'b': 10, 30: 10}
testDict.update((('b', 'updateB'),(40, 10)))
print(testDict)
# {'a': 'updateA', 'b': 'updateB', 30: 10, 40: 10}
위처럼 list와 tuple의 형태로도 변경 및 추가가 가능합니다.
3. 값 삭제
3.1. clear
clear()는 요소를 모두 삭제합니다.
testDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 6:'f'}
testDict.clear()
print(testDict)
# {}
4. 반복문 출력
4.1. items, keys, values
딕셔너리(dict)는 iterable 하지 못한 자료형입니다. 이는 차례대로 반복할 수 없는 자료형이라는 의미입니다.
그렇기 때문에 저장하고 있는 값들에 대한 순서가 보장되지 않습니다.
(Python3.6 이후 버전부터는 순서 보장이 된다고 합니다.)
하지만 items(), keys(), values() 메소드를 활용하면 반복문 (for)를 통해 'key', 'value'를 꺼낼 수 있습니다.
print(type(testDict.items()), testDict.items())
print(type(testDict.keys()), testDict.keys())
print(type(testDict.values()), testDict.values())
# <class 'dict_items'> dict_items([('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), (6, 'f')])
# <class 'dict_keys'> dict_keys(['a', 'b', 'c', 'd', 'e', 6])
# <class 'dict_values'> dict_values([1, 2, 3, 4, 5, 'f'])
타입과 값을 출력해 보면 dict에 정의된 클래스로 출력됩니다.
이를 아래와 같이 적용하면 반복문에서 값을 꺼낼 수 있습니다.
testDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5}
for key, value in testDict.items():
print('key : {} / value : {}'.format(key, value))
# key : a / value : 1
# key : b / value : 2
# key : c / value : 3
# key : d / value : 4
# key : e / value : 5
for key in testDict.keys():
print('key : {}'.format(key))
# key : a
# key : b
# key : c
# key : d
# key : e
for value in testDict.values():
print('value : {}'.format(value))
# value : 1
# value : 2
# value : 3
# value : 4
# value : 5
'[R&D] 프로그래밍 > Python' 카테고리의 다른 글
[Python] 딕셔너리 (dict) 기본 사용 방법 (0) | 2022.08.04 |
---|---|
[Python] 파이썬 자료형 정리 (0) | 2022.07.15 |
[Python] 슬라이싱 (slicing) 개념 및 사용 방법 (2) | 2022.07.06 |
[Python] 리스트(list)를 Stack, Queue 처럼 사용하기 - pop (0) | 2022.07.05 |
[Python] 리스트(list) method - copy, count, index (0) | 2022.07.03 |
[Python] 리스트(list) 정렬하기 (0) | 2022.07.02 |
[Python] 리스트(list) 사용 방법 (0) | 2022.07.01 |
댓글