Löschen von Elementen und Deren Speicherung in Python
Die Methode pop() in Python-Dictionaries ermöglicht das Entfernen eines Schlüssel-Wert-Paares anhand des Schlüssels und gibt den entsprechenden Wert zurück. Diese Methode ist besonders nützlich, wenn ein Wert extrahiert und gleichzeitig aus dem Dictionary entfernt werden soll.
Die Syntax lautet:
dictionary.pop(key)
123456789101112book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "copies": 5 } # Remove the 'copies' key and retrieve its value removed_copies = book.pop("copies") print("Updated dictionary:", book) print("Removed value:", removed_copies)
Existiert der Schlüssel nicht im Dictionary, löst Python eine KeyError-Exception aus.
12345678book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813 } # Attempting to remove a non-existent key removed_genre = book.pop("genre")
Swipe to start coding
Gegeben ist das gleiche Dictionary authors_books.
- Entfernen Sie die Bücher von
"Stephen King"aus dem Dictionary und speichern Sie diese in der Variablenkings_books. - Verwenden Sie dazu die Methode
pop().
Lösung
Danke für Ihr Feedback!
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Großartig!
Completion Rate verbessert auf 4
Löschen von Elementen und Deren Speicherung in Python
Swipe um das Menü anzuzeigen
Die Methode pop() in Python-Dictionaries ermöglicht das Entfernen eines Schlüssel-Wert-Paares anhand des Schlüssels und gibt den entsprechenden Wert zurück. Diese Methode ist besonders nützlich, wenn ein Wert extrahiert und gleichzeitig aus dem Dictionary entfernt werden soll.
Die Syntax lautet:
dictionary.pop(key)
123456789101112book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "copies": 5 } # Remove the 'copies' key and retrieve its value removed_copies = book.pop("copies") print("Updated dictionary:", book) print("Removed value:", removed_copies)
Existiert der Schlüssel nicht im Dictionary, löst Python eine KeyError-Exception aus.
12345678book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813 } # Attempting to remove a non-existent key removed_genre = book.pop("genre")
Swipe to start coding
Gegeben ist das gleiche Dictionary authors_books.
- Entfernen Sie die Bücher von
"Stephen King"aus dem Dictionary und speichern Sie diese in der Variablenkings_books. - Verwenden Sie dazu die Methode
pop().
Lösung
Danke für Ihr Feedback!
single