Python Dictionaries

Common dictionary methods

These are common dictionary methods:

  • get(key, default=None)
This method is used to retrieve the value associated with a specific key in a dictionary. It takes two arguments:

- key: The key you want to access the value for.
- default (optional): A default value to return if the key doesn't exist in the dictionary. This argument defaults to None if not provided.

Example:

my_dict = {"name": "David", "age": 35}

value = my_dict.get("name")  # Returns "David" (key exists)

missing_value = my_dict.get("city", "Unknown")  # Returns "Unknown" (key doesn't exist)


  • keys()
This method returns a view object containing all the keys present in the dictionary. This view object is dynamic, meaning any changes made to the dictionary itself will be reflected in the view. However, you cannot directly modify the dictionary through the view.

Example:

my_dict = {"name": "Emily", "age": 28, "city": "Seattle"}

keys_view = my_dict.keys()  # keys_view is a view object

# Print all keys (using a loop)
for key in keys_view:
    print(key)  # Output: name, age, city


  • values()
This method returns a view object containing all the values present in the dictionary. Similar to keys(), it's a dynamic view, reflecting changes in the dictionary.

Example:

my_dict = {"name": "Frank", "age": 42, "occupation": "Teacher"}

values_view = my_dict.values()  # values_view is a view object

# Print all values (using a loop)
for value in values_view:
    print(value)  # Output: Frank, 42, Teacher


  • items()
This method returns a view object containing all the key-value pairs in the dictionary as tuples.
Each tuple in the view represents a single key-value pair.

Example:

my_dict = {"name": "Grace", "age": 30, "city": "Chicago"}

items_view = my_dict.items()  # items_view is a view object

# Print all key-value pairs (using a loop)
for key, value in items_view:
    print(f"{key}: {value}")  # Output: name: Grace, age: 30, city: Chicago


  • pop(key, default=None)
This method removes the key-value pair associated with a specific key from the dictionary and returns the value. It takes two arguments:

- key: The key of the pair you want to remove.
- default (optional): A default value to return if the key doesn't exist. This argument defaults to None if not provided.
Important: Using pop without the default argument and trying to remove a non-existent key will raise a KeyError.

Example:

my_dict = {"name": "Henry", "age": 50}

removed_value = my_dict.pop("age")  # Returns 50 and removes the "age" key-value pair

# Trying to pop a non-existent key without default will raise a KeyError
# missing_value = my_dict.pop("city")  # Raises KeyError

safe_removal = my_dict.pop("city", "N/A")  # Returns "N/A" (key doesn't exist)


  • popitem()
This method removes and returns an arbitrary key-value pair from the dictionary.
You cannot specify which key-value pair to remove; it's chosen from the dictionary internally.

Example:

my_dict = {"name": "Isla", "age": 22, "country": "Canada"}

removed_pair = my_dict.popitem()  # Returns a tuple containing a key-value pair (e.g., ("country", "Canada"))

It's time to take a quiz!

Test your knowledge and see what you've just learned.

What does the get() method return if the specified key does not exist?

Raises a KeyError
Returns a default value
Returns None
Returns an empty string
Check Answer

What does the keys() method return?

A view object of all keys in the dictionary
A list of all values in the dictionary
A tuple of all key-value pairs
A copy of the dictionary
Check Answer

What does the values() method return?

A list of all keys in the dictionary
A view object of all key-value pairs
A view object of all values in the dictionary
A copy of the dictionary
Check Answer

What does the items() method return?

A view object of all keys
A view object of all key-value pairs as tuples
A view object of all values
A copy of the dictionary
Check Answer

What happens if you use pop() on a non-existent key without a default value?

Raises a KeyError
Returns None
Returns a default value
Returns an empty string
Check Answer

What does the popitem() method do?

Removes and returns all key-value pairs
Removes and returns a specified key-value pair
Removes and returns an arbitrary key-value pair
Returns the last key-value pair without removing it
Check Answer