목차

Dictionary

기본

# JSON # 연관배열 # Hash

dic = {"name":"eric", "age":4,  100: 1000, "sort_field":"kk,d"}
print (dic)
dic["city"] = "seoul"
print (dic)
print (dic.keys())
 
for k in dic.keys():
	print(f" Key:={k}:{dic[k]}")
if 'sort_field' in dic:
    print(dic['sort_field'])

in operator

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
 
if 'key1' in my_dict:
    print("Key exists in the dictionary.")
else:
    print("Key does not exist in the dictionary.")

Using the dict.get() Method

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
 
if my_dict.get('key1') is not None:
    print("Key exists in the dictionary.")
else:
    print("Key does not exist in the dictionary.")

Using Exception Handling

my_dict = {'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}
 
try:
    value = my_dict['key1']
    print("Key exists in the dictionary.")
except KeyError:
    print("Key does not exist in the dictionary.")

Additional Points

중첩 딕셔너리의 할당과 복사 알아보기

그럼 딕셔너리 안에 딕셔너리가 들어있는 중첩 딕셔너리도 copy 메서드로 복사하면 될까요? 다음과 같이 중첩 딕셔너리를 만든 뒤 copy 메서드로 복사합니다.

>>> x = {'a': {'python': '2.7'}, 'b': {'python': '3.6'}}
>>> y = x.copy()

이제 y['a']['python'] = '2.7.15'와 같이 y의 값을 변경해보면 x와 y에 모두 반영됩니다.

>>> y['a']['python'] = '2.7.15'
>>> x
{'a': {'python': '2.7.15'}, 'b': {'python': '3.6'}}
>>> y
{'a': {'python': '2.7.15'}, 'b': {'python': '3.6'}}

중첩 딕셔너리를 완전히 복사하려면 copy 메서드 대신 copy 모듈의 deepcopy 함수를 사용해야 합니다.

>>> x = {'a': {'python': '2.7'}, 'b': {'python': '3.6'}}
>>> import copy             # copy 모듈을 가져옴
>>> y = copy.deepcopy(x)    # copy.deepcopy 함수를 사용하여 깊은 복사
>>> y['a']['python'] = '2.7.15'
>>> x
{'a': {'python': '2.7'}, 'b': {'python': '3.6'}}
>>> y
{'a': {'python': '2.7.15'}, 'b': {'python': '3.6'}}

이제 딕셔너리 y의 값을 변경해도 딕셔너리 x에는 영향을 미치지 않습니다. copy.deepcopy 함수는 중첩된 딕셔너리에 들어있는 모든 딕셔너리를 복사하는 깊은 복사(deep copy)를 해줍니다.

지금까지 딕셔너리의 다양한 메서드와 응용 방법을 배웠는데, 내용이 다소 어려웠습니다. 딕셔너리의 메서드는 모두 외우지 않아도 되며 파이썬을 사용하다 보면 자연스럽게 익히게 됩니다. 여기서는 딕셔너리에 반복문을 사용하는 방법이 중요합니다. 다른 부분은 필요할 때 다시 돌아와서 찾아보세요.