Remove an item from a dictionary in Python (clear, pop, popitem, del) | note.nkmk.me (2024)

In Python, you can remove an item (key-value pair) from a dictionary (dict) using the clear(), pop(), popitem() methods, or the del statement. You can also remove items that satisfy the conditions using dictionary comprehensions.

Contents

  • Remove all items from a dictionary: clear()
  • Remove an item by key and return its value: pop()
  • Remove an item and return its key and value: popitem()
  • Remove an item by key: del
  • Remove items that satisfy a condition: Dictionary comprehensions

See the following article for how to add items to a dictionary.

  • Merge multiple dictionaries and add items to a dictionary in Python

Remove all items from a dictionary: clear()

The clear() method removes all items from a dictionary, making it empty.

d = {'k1': 1, 'k2': 2, 'k3': 3}d.clear()print(d)# {}

Remove an item by key and return its value: pop()

The pop() method removes the item associated with the specified key from the dictionary and returns its value.

Built-in Types - dict.pop() — Python 3.11.3 documentation

By default, specifying a non-existent key raises a KeyError.

d = {'k1': 1, 'k2': 2, 'k3': 3}# removed_value = d.pop('k4')# print(d)# KeyError: 'k4'

You can pass a second argument as a default value to pop(). If the specified key doesn't exist, this value is returned, and the dictionary remains unchanged.

d = {'k1': 1, 'k2': 2, 'k3': 3}removed_value = d.pop('k4', None)print(d)# {'k1': 1, 'k2': 2, 'k3': 3}print(removed_value)# None

Remove an item and return its key and value: popitem()

The popitem() method removes an item from a dictionary and returns its key and value as a tuple, (key, value).

Since Python 3.7, the order of elements in the dictionary is preserved. As a result, popitem() removes elements in LIFO (last in, first out) order.

A KeyError is raised for an empty dictionary.

d = {'k1': 1, 'k2': 2}k, v = d.popitem()print(k)print(v)print(d)# k2# 2# {'k1': 1}k, v = d.popitem()print(k)print(v)print(d)# k1# 1# {}# k, v = d.popitem()# KeyError: 'popitem(): dictionary is empty'

Remove an item by key: del

You can also use the del statement to delete an item from a dictionary.

d = {'k1': 1, 'k2': 2, 'k3': 3}del d['k2']print(d)# {'k1': 1, 'k3': 3}

You can remove multiple items at once.

d = {'k1': 1, 'k2': 2, 'k3': 3}del d['k1'], d['k3']print(d)# {'k2': 2}

If a non-existent key is specified, a KeyError is raised.

d = {'k1': 1, 'k2': 2, 'k3': 3}# del d['k4']# print(d)# KeyError: 'k4'

Remove items that satisfy a condition: Dictionary comprehensions

You can remove items that meet certain conditions from a dictionary using dictionary comprehensions, which are the dictionary equivalent of list comprehensions.

  • List comprehensions in Python

Removing items that satisfy a condition is equivalent to extracting items that do not satisfy the condition.

For example, to remove items with odd values, you can extract items with even values. The same applies to the opposite case.

d = {'apple': 1, 'banana': 10, 'orange': 100}dc = {k: v for k, v in d.items() if v % 2 == 0}print(dc)# {'banana': 10, 'orange': 100}dc = {k: v for k, v in d.items() if v % 2 == 1}print(dc)# {'apple': 1}

The items() method of dict is used to extract keys and values.

  • Iterate through dictionary keys and values in Python

You can also specify conditions based on the keys.

dc = {k: v for k, v in d.items() if k.endswith('e')}print(dc)# {'apple': 1, 'orange': 100}dc = {k: v for k, v in d.items() if not k.endswith('e')}print(dc)# {'banana': 10}

You can use and and or to specify multiple conditions.

  • Boolean operators in Python (and, or, not)
dc = {k: v for k, v in d.items() if v % 2 == 0 and k.endswith('e')}print(dc)# {'orange': 100}
Remove an item from a dictionary in Python (clear, pop, popitem, del) | note.nkmk.me (2024)
Top Articles
How to Invest in Cryptocurrency: Where and How to Start - NerdWallet
How to Invest In Cryptocurrencies: The Basics - Decrypt
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Ffxiv Palm Chippings
Mileage To Walmart
Steamy Afternoon With Handsome Fernando
360 Training Alcohol Final Exam Answers
Bhad Bhabie Shares Footage Of Her Child's Father Beating Her Up, Wants Him To 'Get Help'
今月のSpotify Japanese Hip Hopベスト作品 -2024/08-|K.EG
Hartland Liquidation Oconomowoc
Huge Boobs Images
Rainfall Map Oklahoma
Justified Official Series Trailer
2020 Military Pay Charts – Officer & Enlisted Pay Scales (3.1% Raise)
Mahpeople Com Login
Forest Biome
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Military life insurance and survivor benefits | USAGov
Scream Queens Parents Guide
Highmark Wholecare Otc Store
St Clair County Mi Mugshots
THE FINALS Best Settings and Options Guide
Meridian Owners Forum
Access a Shared Resource | Computing for Arts + Sciences
Allegheny Clinic Primary Care North
My Dog Ate A 5Mg Flexeril
Filmy Met
Ofw Pinoy Channel Su
"Pure Onyx" by xxoom from Patreon | Kemono
Manuel Pihakis Obituary
RFK Jr., in Glendale, says he's under investigation for 'collecting a whale specimen'
The Wichita Beacon from Wichita, Kansas
Senior Houses For Sale Near Me
Wal-Mart 2516 Directory
Jasgotgass2
Www Usps Com Passport Scheduler
Live Delta Flight Status - FlightAware
Lyndie Irons And Pat Tenore
Dragon Ball Super Super Hero 123Movies
Divinity: Original Sin II - How to Use the Conjurer Class
Kenwood M-918DAB-H Heim-Audio-Mikrosystem DAB, DAB+, FM 10 W Bluetooth von expert Technomarkt
The Largest Banks - ​​How to Transfer Money With Only Card Number and CVV (2024)
Lebron James Name Soundalikes
Lesson 5 Homework 4.5 Answer Key
6463896344
Marine Forecast Sandy Hook To Manasquan Inlet
Nfl Espn Expert Picks 2023
2121 Gateway Point
Gameplay Clarkston
Pauline Frommer's Paris 2007 (Pauline Frommer Guides) - SILO.PUB
Latest Posts
Article information

Author: Eusebia Nader

Last Updated:

Views: 6102

Rating: 5 / 5 (80 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Eusebia Nader

Birthday: 1994-11-11

Address: Apt. 721 977 Ebert Meadows, Jereville, GA 73618-6603

Phone: +2316203969400

Job: International Farming Consultant

Hobby: Reading, Photography, Shooting, Singing, Magic, Kayaking, Mushroom hunting

Introduction: My name is Eusebia Nader, I am a encouraging, brainy, lively, nice, famous, healthy, clever person who loves writing and wants to share my knowledge and understanding with you.