Pythona | Sposoby usunięcia klucza ze słownika

Słownik jest używany w różnorodnych praktycznych zastosowaniach, takich jak programowanie na co dzień, tworzenie stron internetowych i programowanie AI/ML, co czyni go ogólnie użytecznym kontenerem. Dlatego znajomość skrótów umożliwiających realizację różnych zadań związanych z korzystaniem ze słownika zawsze jest zaletą. W tym artykule omówiono jedno z takich zadań, jakim jest usuwanie pary klucz-wartość słownika ze słownika. Omówimy różne metody wykonania danego zadania, a w ostatniej części zobaczymy, jak możemy usunąć wszystkie klucze ze słownika. Słownik .

Przykład:

 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} 

Metoda 1: Usuń klucz ze słownika za pomocą polecenia del

Słowo kluczowe del może zostać użyte do lokalnego usunięcia klucza znajdującego się w słowniku w Pythonie. Wadą takiego rozwiązania jest to, że zgłasza wyjątek, jeśli klucz nie zostanie znaleziony, a zatem należy zająć się nieistnieniem klucza. Demonstracja usuwania pary klucz-wartość za pomocą del.

Python3




# 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'> ]>

Wyjście :

The dictionary before performing remove is : {'Arushi': 22, 'Mani': 21, 'Haritha': 21} The dictionary after remove is : {'Arushi': 22, 'Haritha': 21} 

Wyjątek :

Traceback (most recent call last): File '/home/44db951e7011423359af4861d475458a.py', line 20, in del test_dict['Mani'] KeyError: 'Mani' 

Złożoność czasowa inicjowania słownika i usuwania pozycji ze słownika za pomocą instrukcji del wynosi O(1).

Przestrzeń pomocnicza wymagana dla tego kodu to O(1), ponieważ modyfikujemy jedynie istniejący słownik i nie tworzymy żadnych nowych struktur danych.

Metoda 2: Usuń klucz ze słownika za pomocą pop()

The Muzyka pop() można użyć do usunięcia klucza i jego wartości w miejscu. Zaletą w porównaniu z użyciem del jest to, że zapewnia mechanizm drukowania żądanej wartości w przypadku próby usunięcia nieistniejącego słownika. para. Po drugie, oprócz wykonania prostej operacji usuwania, zwraca także wartość usuwanego klucza. Demonstracja usuwania pary klucz-wartość za pomocą pop()

Python3




# 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))>

Wyjście:

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 

Złożoność czasowa: O(1)
Przestrzeń pomocnicza: O(1)

Metoda 3: Użycie items() + rozumienie dyktowania w celu usunięcia klucza ze słownika

items () w połączeniu ze zrozumieniem dyktatu może również pomóc nam w wykonaniu zadania polegającego na usunięciu pary klucz-wartość, ale ma tę wadę, że nie jest dyktandem na miejscu. technika. Właściwie tworzony jest nowy dykt, z wyjątkiem klucza, którego nie chcemy dołączać. Demonstracja usuwania pary klucz-wartość przy użyciu items() + zrozumienie dyktowania.

Python3




# 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))>

Wyjście:

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} 

Złożoność czasowa: O(n), gdzie n jest długością listy test_dict
Przestrzeń pomocnicza: O(n) tworzona jest dodatkowa przestrzeń o rozmiarze n, gdzie n jest liczbą elementów na liście res

Metoda 4: Użyj zrozumienia słownika języka Python, aby usunąć klucz ze słownika

W tym przykładzie użyjemy funkcji rozumienia słownika do usunięcia klucza ze słownika.

Python3




# 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)>

Wyjście:

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} 

Metoda 5: Iteracja i eliminacja

W tym przykładzie użyjemy a pętla aby usunąć klucz ze słownika.

Python3




# 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)>

Wyjście:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} {'Anuradha': 21, 'Mani': 21, 'Haritha': 21} 

Jak usunąć wszystkie klucze ze słownika?

Metoda 1: Usuń wszystkie klucze ze słownika za pomocą polecenia del

Słowa kluczowego del można także używać do usuwania listy, dzielenia listy, usuwania słowników, usuwania par klucz-wartość ze słownika, usuwania zmiennych itp.

Python3




# 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!'> )>

Wyjście:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Deleted! 

Metoda 2: Usuń wszystkie klucze ze słownika za pomocą dict.clear()

Metoda clear() usuwa wszystkie elementy ze słownika. Metoda clear() nie zwraca żadnej wartości.

Python3




# 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)>

Wyjście:

{'Arushi': 22, 'Anuradha': 21, 'Mani': 21, 'Haritha': 21} Length 0 {} 

Złożoność czasowa: O(1)

Przestrzeń pomocnicza: O(1)