Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте Використання Методу pop(): Видалення Елементів з Поверненням Значень | Словник
Структури даних Python

book
Використання Методу pop(): Видалення Елементів з Поверненням Значень

Метод pop() у словниках Python дозволяє видалити пару ключ-значення на основі її ключа та повертає відповідне значення. Цей метод особливо корисний, коли потрібно витягти та обробити значення, одночасно видаляючи його зі словника.

Синтаксис:

dictionary.pop(key)
book = {
"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)
123456789101112
book = { "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)
copy

Якщо ключ не існує у словнику, Python викликає виключення KeyError.

book = {
"title": "Pride and Prejudice",
"author": "Jane Austen",
"year": 1813
}

# Attempting to remove a non-existent key
removed_genre = book.pop("genre")
12345678
book = { "title": "Pride and Prejudice", "author": "Jane Austen", "year": 1813 } # Attempting to remove a non-existent key removed_genre = book.pop("genre")
copy
Завдання

Swipe to start coding

Вам надано той самий словник authors_books.

  • Видаліть книги "Stephen King" зі словника та збережіть їх у змінній kings_books.
  • Використовуйте метод pop() для цього.

Рішення

authors_books = {
'William Shakespeare': ['Hamlet', 'Macbeth', 'Romeo and Juliet', 'Othello'],
'J.K. Rowling': ['Harry Potter and the Sorcerer\'s Stone', 'Harry Potter and the Chamber of Secrets', 'Harry Potter and the Prisoner of Azkaban', 'Harry Potter and the Goblet of Fire'],
'George Orwell': ['1984', 'Animal Farm', 'Coming Up for Air'],
'Stephen King': ['It', 'The Shining', 'Carrie', 'Misery'],
'Agatha Christie': ['Murder on the Orient Express', 'The Murder of Roger Ackroyd', 'And Then There Were None', 'Death on the Nile']
}

# Write your code here
kings_books = authors_books.pop('Stephen King')

# Testing
print(f"Updated dictionary: {authors_books}.\nStephen King\'s books: {kings_books}")
Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 2. Розділ 6
authors_books = {
'William Shakespeare': ['Hamlet', 'Macbeth', 'Romeo and Juliet', 'Othello'],
'J.K. Rowling': ['Harry Potter and the Sorcerer\'s Stone', 'Harry Potter and the Chamber of Secrets', 'Harry Potter and the Prisoner of Azkaban', 'Harry Potter and the Goblet of Fire'],
'George Orwell': ['1984', 'Animal Farm', 'Coming Up for Air'],
'Stephen King': ['It', 'The Shining', 'Carrie', 'Misery'],
'Agatha Christie': ['Murder on the Orient Express', 'The Murder of Roger Ackroyd', 'And Then There Were None', 'Death on the Nile']
}

# Write your code here
kings_books = ___

# Testing
print(f"Updated dictionary: {authors_books}.\nStephen King\'s books: {kings_books}")
toggle bottom row
some-alt