딕셔너리는 변하지 않는 고유한 키(key)와 변하는 값(value)으로 맵핑되어 있는 순서가 없는 집합입니다. 각 키는 값 콜론 (:)으로 구분되고 항목은 쉼표로 구분되며 전체는 중괄호로 묶입니다. 딕셔너리 요소에 액세스하려면 대괄호를 키와 함께 사용하여 값을 가져올 수 있습니다.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print "dict['Name']: ", dict['Name']
print "dict['Age']: ", dict['Age']
아래 예제와 같이 새 항목 또는 키:값 쌍을 추가하거나 기존 항목을 수정하거나 기존 항목을 삭제하여 딕셔너리를 업데이트 할 수 있습니다.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
개별 딕셔너리 요소를 제거하거나 딕셔너리의 전체 내용을 지울 수 있습니다. del 문을 사용하여 한 번에 전체 딕셔너리를 삭제할 수도 있습니다.
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
del dict['Name']; # remove entry with key 'Name'
dict.clear(); # remove all entries in dict
del dict ; # delete entire dictionary
print "dict['Age']: ", dict['Age']
print "dict['School']: ", dict['School']
위의 코드를 실행하면 del dict문 실행으로 딕셔너리가 더 이상 존재하지 않기 때문에 예외 에러가 발생합니다.
dict['Age']:
Traceback (most recent call last):
File "test.py", line 8, in <module>
print "dict['Age']: ", dict['Age'];
TypeError: 'type' object is unsubscriptable
딕셔너리 키에 대해 기억해야 할 두 가지 중요한 사항이 있습니다.
-
중복 키가 허용되지 않는다. 할당 중 중복 키가 발견되면 마지막으로 할당된 값이 사용됩니다.
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
print "dict['Name']: ", dict['Name']
- 키는 불변이어야 합니다. 즉, 문자열, 숫자 또는 튜플을 사전 키로 사용할 수 있지만 ['key']와 같은 것은 허용되지 않는다.
다음과 같은 딕셔너리 함수와 메서드들이 있습니다.
cmp(dict1, dict2) | 두 dictionary의 요소를 비교합니다. |
---|---|
len(dict) | Dictionary의 전체 길이를 제공합니다. 이것은 dictionary에 있는 항목의 수와 같습니다. |
str(dict) | dictionary의 인쇄 가능한 문자열 표현을 생성합니다. |
type(variable) | 전달된 변수의 유형을 반환합니다. |
dict.clear() | dictionary dict의 모든 요소를 제거합니다. |
dict.copy() | dictionary dict의 얕은 복사본을 반환합니다. |
dict.fromkeys() | seq의 키와 값을 value로 설정하여 새 dictionary를 만듭니다. |
dict.get(key, default=None) | 키에 해당 하는 값을 리턴, 키가 dictionary에 없는 경우 default를 리턴 |
dict.has_key(key) | dictionary dict에 key가 있으면 true 그렇지 않으면 false를 반환합니다. |
dict.items() | dict (키, 값) 튜플 쌍의 목록을 반환 |
dict.keys() | dict의 키 리스트를 반환 |
dict.setdefault(key, default=None) | get ()과 유사하지만 키가 dict에 없는 경우 dict [key] = default로 설정 |
dict.update(dict2) | dictionary dict2의 키 - 값 쌍을 dict에 추가 |
dict.values() | dictionary dict의 값 목록을 반환 |