- Python Dictionary Pop vs Popitem
- How to remove items from a dictionary?
- The pop() function
- The popitem() function
- Author
- Python dictionary popitem() method [With Examples]
- Dictionary popitem() method in Python
- Python Dictionary popitem() method
- popitem() method in Python Dictionary Examples
- Conclusion
- Словари (dict) и работа с ними. Методы словарей
- Методы словарей
Python Dictionary Pop vs Popitem
In python, the dictionary functions pop() and popitem() are used to remove items from a dictionary. In this tutorial we’ll look at these functions, their syntax and use-cases along with some examples.
Before we proceed, here’s a quick refresher on dictionaries in python – Dictionaries are a collection of items used for storing key to value mappings. They are mutable and hence we can update the dictionary by adding new key-value pairs, removing existing key-value pairs, or changing the value corresponding to a key. For more, check out our guide on dictionaries and other data structures in python.
How to remove items from a dictionary?
The python dictionary functions pop() and popitem() are used to remove items from a dictionary. The pop() function removes the key-value pair of the key passed whereas the popitem() function removes the last (based on LIFO order) key-value pair from the dictionary.
The pop() function
The pop() dictionary function is used to remove a key from a dictionary and return its value. The following is the syntax:
sample_dict.pop(key, default)
Here, sample_dict is the dictionary from which you want to remove the items.
- key: The key corresponding to the key-value pair you want to remove from the dictionary.
- default (optional): The value to be returned if the key is not present in the dictionary.
- If the key is in the dictionary, it removes the key and returns its value.
- If the key is not in the dictionary and the default is not provided, it raises a KeyError .
- If the key is not in the dictionary and the default is provided, it returns the default.
Example 1: Key present in the dictionary
# dictionary of a sample portfolio shares = # print the dictionary print("Shares original:", shares) # remove 'GOOG' from shares returned_val = shares.pop('GOOG') # print the dictionary print("Shares after removing GOOG:", shares) print("Return value from pop:", returned_val)
Shares original: Shares after removing GOOG: Return value from pop: 50
In the above example, we remove the key ‘GOOG’ from the dictionary shares using the pop() function. It removed the key from the dictionary and returned 50 , the value corresponding to the removed key.
Example 2: Key not present in the dictionary and default not specified.
# dictionary of a sample portfolio shares = # print the dictionary print("Shares original:", shares) # remove 'GOOG' from shares returned_val = shares.pop('TSLA') # print the dictionary print("Shares after removing TSLA:", shares) print("Return value from pop:", returned_val)
Shares original: --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in 6 7 # remove 'GOOG' from shares ----> 8 returned_val = shares.pop('TSLA') 9 10 # print the dictionary KeyError: 'TSLA'
In the above example, we try to remove ‘TSLA’ which is not present in the dictionary using the pop() function. Since no default return value is specified, it resulted in a KeyError .
Example 3: Key not present but default specified.
# dictionary of a sample portfolio shares = # print the dictionary print("Shares original:", shares) # remove 'GOOG' from shares returned_val = shares.pop('TSLA', "Not present in dictionary") # print the dictionary print("Shares after removing TSLA:", shares) print("Return value from pop:", returned_val)
Shares original: Shares after removing TSLA: Return value from pop: Not present in dictionary
In the above example, we again try to remove ‘TSLA’ which is not present in the dictionary but this time we provide the default value to be returned. The dictionary shares remains unchanged before and after the pop() function and we get our custom «Not present in dictionary» as the return value.
The popitem() function
The dictionary function popitem() removes and returns the last key-value pair from the dictionary. That is, it removes items based on the Last-In-First-Out (LIFO) order. The following is the syntax:
Here, sample_dict is the dictionary from which you want to remove the items.
Parameters: The popitem() function does not take any parameters.
Returns: It removes and returns the last (key, value) pair from the dictionary. If the dictionary is empty, it raises a KeyError .
Note: From Python version 3.7, the LIFO order is guaranteed. In prior versions, the popitem() function would return an arbitrary key-value pair from the dictionary.
Example 1: Removing the last dictionary item
# dictionary of a sample portfolio shares = # print the dictionary print("Shares:", shares) # remove item print("Removing item using popitem") returned_val = shares.popitem() print("Return Value:", returned_val) print("Shares:", shares) # add a new item to the dictionary print("Adding a new item to shares") shares.update() print("Shares:", shares) # remove item print("Removing item using popitem") returned_val = shares.popitem() print("Return Value:", returned_val) print("Shares:", shares)
Shares: Removing item using popitem Return Value: ('MSFT', 200) Shares: Adding a new item to shares Shares: Removing item using popitem Return Value: ('TSLA', 80) Shares:
In the above example, the popitem() function is used to remove items from the dictionary shares . It removes the last (key, value) pair from the dictionary and returns it.
Example 2: Using popitem() on an empty dictionary
# empty dictionary shares = <> # print the dictionary print("Shares:", shares) # remove item print("Removing item using popitem") returned_val = shares.popitem() print("Return Value:", returned_val) print("Shares:", shares)
Shares: <> Removing item using popitem --------------------------------------------------------------------------- KeyError Traceback (most recent call last) in 6 # remove item 7 print("Removing item using popitem") ----> 8 returned_val = shares.popitem() 9 print("Return Value:", returned_val) 10 print("Shares:", shares) KeyError: 'popitem(): dictionary is empty'
In the above example, a KeyError is raised on using the popitem() function on an empty dictionary.
For more on python dictionary functions, refer to the python docs.
Tutorials on python dictionaries –
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.
Author
Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects. View all posts
Python dictionary popitem() method [With Examples]
In this article, we will discuss the Python Dictionary popitem() method which is a useful function that facilitates the removal of elements from a dictionary.
In addition to this, we will discuss the popitem() method syntax, usage, and examples.
Dictionary popitem() method in Python
Below are the topics that we are doing to discuss in this article:
- Introduction to Python Dictionary popitem() method
- Syntax of the popitem() method
- Purpose and use cases of the popitem() method
Python Dictionary popitem() method
The popitem() method in Python is a built-in method used with dictionaries. It removes and returns the last key-value pair inserted into the Python dictionary as a tuple. This method is useful when we need to remove items from a Python dictionary while also retrieving their key-value pairs.
Syntax of the popitem() Method is as follows:
popitem() method in Python Dictionary Examples
Let’s dive into some examples to better understand the popitem() method in action:
Example#1 Using the popitem() Method
student_data = removed_item = student_data.popitem() print("Removed item:", removed_item) print("Updated dictionary:", student_data)
The popitem() method is primarily used to remove the last item in a Python dictionary. As shown, the last item in the student_data Python dictionary (‘Course’, ‘Computer Science’) is removed using the popitem() method, and the remaining Python dictionary only contains ‘Name’ and ‘Age’ .
Example#2 Handling Empty Dictionaries
empty_dict = <> try: removed_item = empty_dict.popitem() except KeyError: print("The dictionary is empty.")
When the popitem() method is applied to an empty Python dictionary, a KeyError is raised. To avoid this, we can use exception handling to display a custom error message.
Example#3 Removing a State from a List of States and Capitals
states_and_capitals = < 'California': 'Sacramento', 'Texas': 'Austin', 'Florida': 'Tallahassee', 'New York': 'Albany', 'Illinois': 'Springfield' >removed_state_and_capital = states_and_capitals.popitem() print("Removed state and capital:", removed_state_and_capital) print("Remaining states and capitals:", states_and_capitals)
In this example, the popitem() method removes the last state-capital pair (‘Illinois’, ‘Springfield’) from the Python dictionary. The remaining states and capitals are then printed.
Example#4 Picking a Random US State for a Road Trip
Imagine we want to randomly select a US state for a road trip. We can use the popitem() method to remove a state from a Python list of states so it won’t be selected again.
import random us_states = < 1: 'Alabama', 2: 'Alaska', 3: 'Arizona', 4: 'Arkansas', 5: 'California', # More US states. >random_state_key = random.choice(list(us_states.keys())) selected_state = us_states[random_state_key] us_states.popitem() print("Selected state for road trip:", selected_state) print("Remaining states:", us_states)
In this example, a random state key is chosen from the Python list of US states. The popitem() method is then used to remove the last state from the list, ensuring it won’t be chosen again in future iterations.
Conclusion
The Python dictionary popitem() method is an essential function when working with dictionaries in Python. It allows users to remove the last item in a dictionary easily and returns a tuple containing the key-value pair.
You may also like to read the following articles:
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.
Словари (dict) и работа с ними. Методы словарей
Сегодня я расскажу о таком типе данных, как словари, о работе со словарями, операциях над ними, методах, о генераторах словарей.
Словари в Python — неупорядоченные коллекции произвольных объектов с доступом по ключу. Их иногда ещё называют ассоциативными массивами или хеш-таблицами.
Чтобы работать со словарём, его нужно создать. Сделать это можно несколькими способами. Во-первых, с помощью литерала:
Во-вторых, с помощью функции dict:
В-третьих, с помощью метода fromkeys:
В-четвертых, с помощью генераторов словарей, которые очень похожи на генераторы списков.
Теперь попробуем добавить записей в словарь и извлечь значения ключей:
: Как видно из примера, присвоение по новому ключу расширяет словарь, присвоение по существующему ключу перезаписывает его, а попытка извлечения несуществующего ключа порождает исключение. Для избежания исключения есть специальный метод (см. ниже), или можно перехватывать исключение.
Что же можно еще делать со словарями? Да то же самое, что и с другими объектами: встроенные функции, ключевые слова (например, циклы for и while), а также специальные методы словарей.
Методы словарей
dict.clear() — очищает словарь.
dict.copy() — возвращает копию словаря.
classmethod dict.fromkeys(seq[, value]) — создает словарь с ключами из seq и значением value (по умолчанию None).
dict.get(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а возвращает default (по умолчанию None).
dict.items() — возвращает пары (ключ, значение).
dict.keys() — возвращает ключи в словаре.
dict.pop(key[, default]) — удаляет ключ и возвращает значение. Если ключа нет, возвращает default (по умолчанию бросает исключение).
dict.popitem() — удаляет и возвращает пару (ключ, значение). Если словарь пуст, бросает исключение KeyError. Помните, что словари неупорядочены.
dict.setdefault(key[, default]) — возвращает значение ключа, но если его нет, не бросает исключение, а создает ключ со значением default (по умолчанию None).
dict.update([other]) — обновляет словарь, добавляя пары (ключ, значение) из other. Существующие ключи перезаписываются. Возвращает None (не новый словарь!).
dict.values() — возвращает значения в словаре.
Для вставки кода на Python в комментарий заключайте его в теги