티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
How to copy a dictionary and only edit the copy
딕셔너리 복사 후 사본만 편집하기
문제 내용
I set dict2 = dict1
. When I edit dict2
, the original dict1
also changes. Why?
dict2 = dict1로 설정합니다. dict2를 편집하면 원본 dict1도 바뀝니다. 왜죠?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key2': 'WHY?!', 'key1': 'value1'}
높은 점수를 받은 Solution
Python never implicitly copies objects. When you set dict2 = dict1
, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.
Python은 절대로 암묵적으로 객체를 복사하지 않는다. dict2 = dict1을 설정하면 동일한 dict 개체를 참조하게 되므로 변환할 때 해당 개체에 대한 모든 참조가 현재 상태의 개체를 계속 참조합니다.
If you want to copy the dict (which is rare), you have to do so explicitly with
만약 당신이 딕셔너리를 복사하고 싶다면, 당신은 명시적으로 그렇게 해야 한다.
dict2 = dict(dict1)
or
또는
dict2 = dict1.copy()
가장 최근 달린 Solution
In addition to the other provided solutions, you can use **
to integrate the dictionary into an empty dictionary, e.g.,
제공된 다른 솔루션 외에도 **를 사용하여 빈 딕셔너리에 통합할 수 있습니다. 예:
shallow_copy_of_other_dict = {**other_dict}
.
slight_copy_of_other_messages = {**other_messages}.
Now you will have a "shallow" copy of other_dict
.
이제 other_dict의 "shallow" 복사본을 갖게 됩니다.
Applied to your example:
예제에 적용:
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = {**dict1}
>>> dict2
{'key1': 'value1', 'key2': 'value2'}
>>> dict2["key2"] = "WHY?!"
>>> dict1
{'key1': 'value1', 'key2': 'value2'}
>>>
Pointer: Difference between shallow and deep copys
포인터: 얕은 복사와 깊은 복사의 차이
출처 : https://stackoverflow.com/questions/2465921/how-to-copy-a-dictionary-and-only-edit-the-copy
'개발 > 파이썬' 카테고리의 다른 글
데이터 프레임 열 순서 변경하기 (0) | 2022.12.06 |
---|---|
Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session' 에러 수정하기 (0) | 2022.12.06 |
Python을 사용하여 리스트 내용을 파일에 쓰기 (0) | 2022.12.06 |
비어 있지 않은 폴더 삭제하기 (0) | 2022.12.06 |
파이썬에서 파일 크기 확인하기 (0) | 2022.12.05 |