티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Delete an element from a dictionary

Dictionary에서 아이템(요소) 삭제

 문제 내용 

How do I delete an item from a dictionary in Python?

파이썬에서 Dictionary에서 항목을 삭제하려면 어떻게 해야 합니까?

 

Without modifying the original dictionary, how do I obtain another dict with the item removed?

원본 Dictionary를 수정하지 않고 항목을 제거한 상태에서 다른 Dictionary를 얻는 방법은 무엇입니까?

 

 

 

 높은 점수를 받은 Solution 

The del statement removes an element:

del 문은 요소를 제거합니다.
del d[key]

 

Note that this mutates the existing dictionary, so the contents of the dictionary changes for anybody else who has a reference to the same instance. To return a new dictionary, make a copy of the dictionary:

이것은 기존 Dictionary를 변형하므로, 동일한 인스턴스에 대한 참조가 있는 다른 사용자에 대해 Dictionary의 내용이 변경됩니다. 새 Dictionary를 반환하려면 복사본을 만드세요.
def removekey(d, key):
    r = dict(d)
    del r[key]
    return r

 

The dict() constructor makes a shallow copy. To make a deep copy, see the copy module.

dict() 생성자가 얕은 복사본을 만듭니다. 전체 복사본을 만들려면 복사 모듈을 참조하십시오.

Note that making a copy for every dict del/assignment/etc. means you're going from constant time to linear time, and also using linear space. For small dicts, this is not a problem. But if you're planning to make lots of copies of large dicts, you probably want a different data structure, like a HAMT (as described in this answer).

모든 dict del/assignment/etc에 대해 사본을 만드는 점에 유의하십시오. 상수 시간에서 선형 시간으로 이동하고 선형 공간도 사용한다는 의미입니다. 작은 dicts의 경우 이것은 문제가 되지 않습니다. 그러나 큰 dicts의 사본을 많이 만들 계획이라면 HAMT와 같은 다른 데이터 구조를 원할 것입니다(이 답변에 함).

 

 

 

 가장 최근 달린 Solution 

Solution 1: with deleting

솔루션 1: 삭제와 함께..
info = {'country': 'Iran'}
country = info.pop('country') if 'country' in info else None

 

Solution 2: without deleting

솔루션 2: 삭제하지 않고..
info = {'country': 'Iran'}
country = info.get('country') or None

 

 

출처 : https://stackoverflow.com/questions/5844672/delete-an-element-from-a-dictionary

반응형
댓글
공지사항
최근에 올라온 글