Dictionary는 일일 프로그래밍, 웹 개발, AI/ML 프로그래밍 등 다양한 실용적인 애플리케이션에도 사용되므로 전반적으로 유용한 컨테이너입니다. 따라서 사전 사용과 관련된 다양한 작업을 수행하기 위한 속기를 아는 것은 항상 장점입니다. 이 기사에서는 사전에서 사전 키-값 쌍을 삭제/제거하는 작업 중 하나를 다루고, 주어진 작업을 처리하는 다양한 방법에 대해 논의하고, 마지막으로 사전에서 모든 키를 삭제하는 방법을 살펴보겠습니다. 사전 .
예:
Before remove key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21 } Operation Perform: del test_dict['Mani'] After removing key: {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}> 방법 1: del을 사용하여 사전에서 키 제거
del 키워드는 Python 사전에 있는 키를 내부 삭제하는 데 사용할 수 있습니다. 이것을 사용할 때 생각할 수 있는 한 가지 단점은 키를 찾을 수 없으면 예외가 발생하므로 키가 존재하지 않는 경우를 처리해야 한다는 것입니다. del을 사용하여 키-값 쌍 삭제를 보여줍니다.
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is : '>, test_dict)> # Using del to remove a dict> # removes Mani> del> test_dict[>'Mani'>]> # Printing dictionary after removal> print>(>'The dictionary after remove is : '>, test_dict)> # Using del to remove a dict> # raises exception> del> test_dict[>'Mani'>]> |
>
>
자바에서 배열을 만드는 방법
출력 :
The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Haritha': 21}> 예외 :
Traceback (most recent call last): File '/home/44db951e7011423359af4861d475458a.py', line 20, in del test_dict['Mani'] KeyError: 'Mani'>
del 문을 사용하여 사전을 초기화하고 사전에서 항목을 제거하는 시간 복잡도는 O(1)입니다.
이 코드에 필요한 보조 공간은 O(1)입니다. 기존 사전만 수정하고 새 데이터 구조는 생성하지 않기 때문입니다.
방법 2: pop()을 사용하여 사전에서 키 제거
그만큼 팝() 키와 해당 값을 삭제하는 데 사용할 수 있습니다. del을 사용하는 것보다 장점은 존재하지 않는 사전을 제거하려고 할 때 원하는 값을 인쇄하는 메커니즘을 제공한다는 것입니다. 쌍. 둘째, 간단한 삭제 작업을 수행하는 것 외에도 제거되는 키의 값도 반환합니다. pop()을 사용하여 키-값 쌍 삭제 시연
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is : '> +> str>(test_dict))> # Using pop() to remove a dict. pair> # removes Mani> removed_value>=> test_dict.pop(>'Mani'>)> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(test_dict))> print>(>'The removed key's value is : '> +> str>(removed_value))> print>(>'
'>)> # Using pop() to remove a dict. pair> # doesn't raise exception> # assigns 'No Key found' to removed_value> removed_value>=> test_dict.pop(>'Manjeet'>,>'No Key found'>)> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(test_dict))> print>(>'The removed key's value is : '> +> str>(removed_value))> |
>
>
제어 구조 파이썬
산출:
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : 21 The dictionary after remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21} The removed key's value is : No Key found> 시간 복잡도: O(1)
보조 공간: O(1)
방법 3: items() + dict comprehension을 사용하여 사전에서 키 제거
dict 이해와 결합된 items()도 키-값 쌍 삭제 작업을 달성하는 데 도움이 될 수 있지만 내부 dict가 아니라는 단점이 있습니다. 기술. 실제로 포함하고 싶지 않은 키를 제외하고 새 사전이 생성됩니다. items() + dict comprehension을 사용하여 키-값 쌍 삭제를 시연합니다.
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,> >'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>('The dictionary before performing> remove>is> : '>+> str>(test_dict))> # Using items() + dict comprehension to remove a dict. pair> # removes Mani> new_dict>=> {key: val>for> key,> >val>in> test_dict.items()>if> key !>=> 'Mani'>}> # Printing dictionary after removal> print>(>'The dictionary after remove is : '> +> str>(new_dict))> |
>
>
산출:
The dictionary before performing remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22, 'Mani': 21} The dictionary after remove is : {'Anuradha': 21, 'Haritha': 21, 'Arushi': 22}> 시간 복잡도: O(n), 여기서 n은 test_dict 목록의 길이입니다.
보조 공간: O(n) 크기 n의 추가 공간이 생성됩니다. 여기서 n은 res 목록의 요소 수입니다.
방법 4: Python Dictionary Comprehension을 사용하여 사전에서 키 제거
이 예에서는 Dictionary Comprehension을 사용하여 사전에서 키를 제거합니다.
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> # Printing dictionary before removal> print>(>'The dictionary before performing remove is :
'> +> str>(test_dict))> a_dict>=> {key: test_dict[key]>for> key>in> test_dict>if> key !>=> 'Mani'>}> print>(>'The dictionary after performing remove is :
'>, a_dict)> |
>
>
산출:
The dictionary before performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} The dictionary after performing remove is : {'Arushi': 22, 'Anuradha': 21, 'Haritha': 21}> 방법 5: 반복 및 제거
이 예에서는 고리 사전에서 키를 제거합니다.
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> y>=> {}> # eliminate the unrequired element> for> key, value>in> test_dict.items():> >if> key !>=> 'Arushi'>:> >y[key]>=> value> print>(y)> |
>
>
산출:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} {'Anuradha': 21, 'Mani': 21, 'Haritha': 21}> 사전에서 모든 키를 삭제하는 방법은 무엇입니까?
방법 1: del을 사용하여 사전에서 모든 키 삭제
del 키워드는 목록 삭제, 목록 분할, 사전 삭제, 사전에서 키-값 쌍 제거, 변수 삭제 등의 작업에도 사용할 수 있습니다.
자바로 설정
파이썬3
맘타 쿨카르니 배우
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> del> test_dict> try>:> >print>(test_dict)> except>:> >print>(>'Deleted!'>)> |
>
>
산출:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Deleted!> 방법 2: dict.clear()를 사용하여 사전에서 모든 키 삭제
Clear() 메소드는 사전에서 모든 항목을 제거합니다. Clear() 메서드는 어떤 값도 반환하지 않습니다.
파이썬3
# Initializing dictionary> test_dict>=> {>'Arushi'>:>22>,>'Anuradha'>:>21>,>'Mani'>:>21>,>'Haritha'>:>21>}> print>(test_dict)> # empty the dictionary d> test_dict.clear()> print>(>'Length'>,>len>(test_dict))> print>(test_dict)> |
>
>
산출:
{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Length 0 {}> 시간 복잡도: 오(1)
보조 공간: 오(1)