문서의 선택한 두 판 사이의 차이를 보여줍니다.
| 양쪽 이전 판이전 판다음 판 | 이전 판 | ||
| python:dictionary [2024/10/15 04:26] – [기본] taekgu | python:dictionary [2025/04/15 10:05] (현재) – 바깥 편집 127.0.0.1 | ||
|---|---|---|---|
| 줄 1: | 줄 1: | ||
| + | ====== Dictionary ====== | ||
| + | ===== 기본 ===== | ||
| + | |||
| + | # JSON | ||
| + | # 연관배열 | ||
| + | # Hash | ||
| + | |||
| + | <code python> | ||
| + | dic = {" | ||
| + | print (dic) | ||
| + | dic[" | ||
| + | print (dic) | ||
| + | print (dic.keys()) | ||
| + | |||
| + | for k in dic.keys(): | ||
| + | print(f" | ||
| + | if ' | ||
| + | print(dic[' | ||
| + | </ | ||
| + | |||
| + | ==== in operator ==== | ||
| + | <code python> | ||
| + | my_dict = {' | ||
| + | |||
| + | if ' | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | ==== Using the dict.get() Method ==== | ||
| + | <code python> | ||
| + | my_dict = {' | ||
| + | |||
| + | if my_dict.get(' | ||
| + | print(" | ||
| + | else: | ||
| + | print(" | ||
| + | </ | ||
| + | ==== Using Exception Handling ==== | ||
| + | <code python> | ||
| + | my_dict = {' | ||
| + | |||
| + | try: | ||
| + | value = my_dict[' | ||
| + | print(" | ||
| + | except KeyError: | ||
| + | print(" | ||
| + | </ | ||
| + | |||
| + | ==== 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 메서드로 복사합니다. | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | </ | ||
| + | 이제 y[' | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | {' | ||
| + | >>> | ||
| + | {' | ||
| + | </ | ||
| + | 중첩 딕셔너리를 완전히 복사하려면 copy 메서드 대신 copy 모듈의 deepcopy 함수를 사용해야 합니다. | ||
| + | |||
| + | <code python> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | >>> | ||
| + | {' | ||
| + | >>> | ||
| + | {' | ||
| + | </ | ||
| + | 이제 딕셔너리 y의 값을 변경해도 딕셔너리 x에는 영향을 미치지 않습니다. copy.deepcopy 함수는 중첩된 딕셔너리에 들어있는 모든 딕셔너리를 복사하는 깊은 복사(deep copy)를 해줍니다. | ||
| + | |||
| + | 지금까지 딕셔너리의 다양한 메서드와 응용 방법을 배웠는데, | ||