1. Learn
  2. /
  3. Courses
  4. /
  5. Data Types for Data Science in Python

Exercise

Popping and deleting from dictionaries

Often, you will want to remove keys and value from a dictionary. You can do so using the del Python instruction. It's important to remember that del will throw a KeyError if the key you are trying to delete does not exist. You can not use it with the .get() method to safely delete items; however, it can be used with try: catch:.

If you want to save that deleted data into another variable for further processing, the .pop() dictionary method will do just that. You can supply a default value for .pop() much like you did for .get() to safely deal with missing keys. It's also typical to use .pop() instead of del since it is a safe method.

Instructions

100 XP
  • Remove "Madison Square Park" from squirrels_by_park and store it as squirrels_madison.
  • Safely remove "City Hall Park" from squirrels_by_park with a empty dictionary as the default and store it as squirrels_city_hall. To do this, pass in an empty dictionary {} as a second argument to .pop().
  • Delete "Union Square Park" from squirrels_by_park.
  • Print squirrels_by_park.