Använda Metoden popitem(): Ta Bort Det Senast Insatta Objektet
Ordböcker har också en popitem()
-metod som tar bort och returnerar det sista nyckel-värdeparet.
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813, "genre": "Romance" } # Removing the last key-value pair using popitem() popped_item = book.popitem() # Printing the updated dictionary and the removed pair print("Removed item:", popped_item) print("Updated dictionary:", book)
Uppgift
Swipe to start coding
Du har fått ordboken authors_books
.
- Ta bort det sista elementet från ordboken.
- Lägg till ett nytt element med nyckeln
'Mark Twain'
och värdet['The Adventures of Tom Sawyer', 'Adventures of Huckleberry Finn', 'The Prince and the Pauper']
. - Använd
popitem()
-metoden för att ta bort det sista elementet.
Lösning
Var allt tydligt?
Tack för dina kommentarer!
Avsnitt 2. Kapitel 7