티스토리 뷰

반응형

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

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

 

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

How can I remove a key from a Python dictionary?

파이썬 Dictionary에서 키 제거하기

 문제 내용 

Is there a one-line way of deleting a key from a dictionary without raising a KeyError?

KeyError를 발생시키지 않고 Dictionary에서 키를 삭제하는 한 줄짜리 방법이 있습니까?

 

if 'key' in my_dict:
    del my_dict['key']

 

 

 높은 점수를 받은 Solution 

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

Dictionary에 키가 있는지 여부에 관계없이 키를 삭제하려면 dict.pop()의 두 인수 형식을 사용합니다.
my_dict.pop('key', None)

 

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop('key')) and key does not exist, a KeyError is raised.

사전에 키가 있으면 my_dict[key]를 반환하고, 그렇지 않으면 없음을 반환합니다. 두 번째 매개 변수가 지정되지 않고(즉, my_dict.pop('key') 키가 존재하지 않으면 KeyError가 발생합니다.

 

To delete a key that is guaranteed to exist, you can also use:

존재하는 것이 보장된 키를 삭제하려면 다음을 사용할 수도 있습니다.
del my_dict['key']

 

This will raise a KeyError if the key is not in the dictionary.

키가 사전에 없는 경우 키 오류가 발생합니다.

 

 

 

 가장 최근 달린 Solution 

Another way is by using items() + dict comprehension.

또 다른 방법은 items() + dict comprehension을 사용하는 것입니다.

 

items() coupled with dict comprehension can also help us achieve the task of key-value pair deletion, but it has the drawback of not being an in place dict technique. Actually a new dict if created except for the key we don’t wish to include.

딕트 이해와 결합된 items()은 키-값 쌍 삭제 작업을 달성하는 데 도움이 될 수 있지만, 인플레이스 딕트 기법이 아니라는 단점이 있다. 사실 우리가 포함하고 싶지 않은 키를 제외하고 새로운 딕트가 생성되었습니다.
test_dict = {"sai" : 22, "kiran" : 21, "vinod" : 21, "sangam" : 21}

# Printing dictionary before removal
print ("dictionary before performing remove is : " + str(test_dict))

# Using items() + dict comprehension to remove a dict. pair
# removes  vinod
new_dict = {key:val for key, val in test_dict.items() if key != 'vinod'}

# Printing dictionary after removal
print ("dictionary after remove is : " + str(new_dict))

 

Output:

출력:
dictionary before performing remove is : {'sai': 22, 'kiran': 21, 'vinod': 21, 'sangam': 21}
dictionary after remove is : {'sai': 22, 'kiran': 21, 'sangam': 21}

 

 

출처 : https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary

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