How To Remove Items From A Dictionary Python
Python Tutorials
Python Remove Central from a Dictionary: A Complete Guide
The Python pop() method and del keyword remove keys from a lexicon. pop() accepts the proper name of the primal you lot desire to remove from the dictionary as an argument. The del keyword stands on its ain and refers to a specific central.
Dictionaries are mutable objects. This means yous tin can change the values dictionaries store. Every bit a effect, you can remove keys from dictionaries at whatever time if they are no longer needed.
Suppose you accept a Python dictionary that stores data about books sold in a bookstore. You may determine to remove a primal that denotes if the volume has been on the managing director'southward recommended listing.
Find Your Bootcamp Lucifer
Career Karma matches you with top tech bootcamps
Access exclusive scholarships and prep courses
By continuing yous agree to our Terms of Service and Privacy Policy , and you lot consent to receive offers and opportunities from Career Karma by phone, text message, and email.
Python Remove Key from Dictionary
To remove a key from a dictionary in Python, utilise the pop() method or the "del" keyword. Both methods work the same in that they remove keys from a dictionary. The popular() method accepts a key name equally argument whereas "del" accepts a dictionary item after the del keyword.
In this guide, nosotros discuss how to remove a primal from a Python dictionary. We'll walk through two examples and then yous can kickoff removing dictionary keys chop-chop.
Remove Key from a Dictionary Python: pop()
The Python popular() method removes an item from a lexicon.
This method tin too be used to remove items from a listing at a particular index value. For this guide, we'll focus on removing an item from a lexicon. Read our tutorial on the Python listing pop() guide for more data on how to remove an particular from a list.
The syntax for this method is:
"Career Karma entered my life when I needed information technology virtually and chop-chop helped me friction match with a bootcamp. 2 months later graduating, I found my dream chore that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
lexicon.pop(key_to_remove, not_found)
The pop() method can have either one or 2 parameters:
- The proper noun of the fundamental yous desire to remove (mandatory).
- The value that should exist returned if a cardinal cannot be plant (optional).
Past default, pop() returns the value associated with the key that removed from a dictionary.
If yous only specify 1 parameter, the interpreter may throw a Python KeyError . This will happen if y'all endeavour to remove an chemical element from a dictionary that does not be.
pop() Example
Nosotros're building a programme that keeps rails of the shoes that are in stock at a local shoe store. Permit's showtime by defining a Python array . This array contains a list of shoes with which we can piece of work:
shoes = [ { "id": 1, "proper noun": "Air Force 1 Mid Casual", "brand": "Nike", "in_stock": True }, { "id": 2, "name": "Blazer Mid '77 Casual", "make": "Nike", "in_stock": True }, { "id": three, "proper noun": "I Take Basketball Shoes", "brand": "Jordan", "in_stock": False } ]
Our list of shoes contains three dictionaries. Each lexicon contains 4 keys: id, name, brand, and in_stock. id is a unique identifier for a shoe. name is the name of a shoe. brand is the brand that manufactures a shoe. in_stock represents whether a shoe is in stock.
The shoe store has decided to remove the "in_stock" fundamental. They want to supercede the key with a new value that tracks how many pairs of each shoe are in stock. To remove the "in_stock" key from our dictionaries, we're going to use the pop() method:
for s in shoes: remove_key = due south.pop("in_stock", None) if remove_key != None: print("in_stock has been removed for the {} shoe.".format(south["proper name"])) else: print("No key has been removed for the {} shoe.".format(s["name"])) impress(shoes)
The beginning parameter in the built-in office pop() is the name of the key we want to remove. Our lawmaking returns the 2nd value if the specified central does not be. By default, the popular() method returns the name of the removed key.
In each iteration of our loop, we check if the "in_stock" key has been removed using an Python if statement . If "remove_key" has a value other than None, it ways our key is removed.
After nosotros remove the "in_stock" cardinal our dictionaries, our code prints our new lexicon to the console. Run our lawmaking and see what happens:
in_stock has been removed for the Air Force 1 Mid Casual shoe. in_stock has been removed for the Blazer Mid '77 Casual shoe. in_stock has been removed for the 1 Accept Basketball game Shoes shoe. [{'id': 1, 'name': 'Air Force i Mid Casual', 'brand': 'Nike'}, {'id': 2, 'proper name': "Blazer Mid '77 Casual", 'brand': 'Nike'}, {'id': iii, 'proper name': 'One Accept Basketball game Shoes', 'brand': 'Jordan'}]
We remove the "in_stock" for all our shoes. Our lawmaking shows u.s.a. that our keys are removed and prints out our updated dictionary to the console.
Remove Primal from a Dictionary Python: del
The Python del argument deletes an object. Because key-value pairs in dictionaries are objects, you tin can delete them using the "del" keyword.
The "del" keyword is used to delete a primal that does be. It raises a KeyError if a key is not present in a dictionary.
Let's take a look at the syntax for this keyword:
Nosotros utilize the indexing notation to recollect the detail from the dictionary we desire to remove. "key" represents the name of the key whose cardinal-value pair we want to remove from the dictionary.
del Example
We're going to build a program that removes a key from an individual dictionary. This dictionary contains detailed information about a item shoe:
shoe = { "id": three, "proper noun": "1 Take Basketball game Shoes", "make": "Jordan", "in_stock": Imitation, "price": 100.00, "colors": ["Gray"], "discount": Simulated }
The shoe store has decided they are not going to discount whatever Jordan shoes. They want to remove the "discount" key from the dictionary. We can do this using the del keyword:
del shoe["discount"] print(shoe)
This code deletes the "discount" key from our listing and shows us the new lexicon:
{'id': 3, 'name': 'One Take Basketball Shoes', 'brand': 'Jordan', 'in_stock': False, 'price': 100.0, 'colors': ['Gray']}
The cardinal "discount" is no longer in our dictionary.
Python pop() vs del
There are two differences between popular() and del.
Get-go, the popular() method returns the value of the cardinal removed from a dictionary whereas del does not render any value.
Second, the del keyword returns a KeyError if a central is not in a dictionary. On the other hand, the pop() method but returns a KeyError if you practise non specify a second parameter. The 2d parameter is the default value to be returned if a key is not present in a dictionary.
Conclusion
Both the pop() method and the del keyword let you remove keys from a lexicon. The pop() method is generally more useful because it is capable of returning a default value if a key is not deleted. This is handy as information technology helps prevent KeyErrors.
Practise you want to learn more than almost coding in Python? Read our How to Learn Python guide . This guide contains a listing of top online courses and learning resources y'all can utilize to build your knowledge of Python.
Almost us: Career Karma is a platform designed to assistance job seekers observe, enquiry, and connect with job preparation programs to advance their careers. Learn almost the CK publication.
What's Next?
-
Want to take activity?
Get matched with elevation bootcamps
-
Want to dive deeper?
Inquire a question to our community
-
Want to explore tech careers?
Take our careers quiz
James Gallagher
X
Detect the right bootcamp for y'all
Many careers in tech pay over $100,000 per year. With assist from Career Karma, you can find a training program that meets your needs and volition set you lot up for a long-term, well-paid career in tech.
By continuing yous agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and electronic mail.
How To Remove Items From A Dictionary Python,
Source: https://careerkarma.com/blog/python-remove-key-from-a-dictionary/
Posted by: siasonviziest.blogspot.com
0 Response to "How To Remove Items From A Dictionary Python"
Post a Comment