사용자 도구

사이트 도구


python:dictionary

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

  • 키 존재 대 값 존재 위에서 논의한 방법은 키가 존재하는지 여부만 확인합니다. 값이 존재하는지 확인하려면 dictname.values()와 같은 방법을 사용하여 값을 재정해야 합니다.
  • Performance considerations Different methods may have different performance implications depending on the size of your dictionary. Generally the in operator is best for small to medium-sized dictionaries while dict.get() and exemption handling are a good fit for large dictionaries.
  • Combining methods A good thing about working with Python dictionary methods is that you can combine them. For example, you can use the in operator to check if a key exists and the dict.get() to retrieve its value if it exists.
  • dict.setdefault()를 사용하면 키가 존재하는지 확인하고 존재하는 경우 값을 반환할 수 있습니다. 키가 누락된 경우, 동시에 사전에 추가하면서 기본값을 설정할 수 있습니다.

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

그럼 딕셔너리 안에 딕셔너리가 들어있는 중첩 딕셔너리도 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)를 해줍니다.

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

python/dictionary.txt · 마지막으로 수정됨: 2025/04/15 10:05 저자 127.0.0.1