What are dictionary methods?

QuestionsQuestions8 SkillsProDec, 15 2025
0162

That's a great follow-up question! Just like lists and sets, dictionaries come with several built-in methods that provide convenient ways to interact with and manipulate their data.

The current step actually introduces three very common and useful dictionary methods: keys(), values(), and items(). Let's dive into these and a few others you'll frequently use.

Common Dictionary Methods:

  1. keys()

    • Purpose: Returns a new view object that displays a list of all the keys in the dictionary.
    • Example from step:
      person = {'name': 'Alice', 'age': 26, 'occupation': 'Engineer', 'city': 'New York'}
      print(person.keys())
      # Output: dict_keys(['name', 'age', 'occupation', 'city'])

    You can then convert this view into a list if you need to: list(person.keys())

  2. values()

    • Purpose: Returns a new view object that displays a list of all the values in the dictionary.
    • Example from step:
      print(person.values())
      # Output: dict_values(['Alice', 26, 'Engineer', 'New York'])

    Similarly, list(person.values()) would give you a list of values.

  3. items()

    • Purpose: Returns a new view object that displays a list of a dictionary's key-value tuple pairs.
    • Example from step:
      print(person.items())
      # Output: dict_items([('name', 'Alice'), ('age', 26), ('occupation', 'Engineer'), ('city', 'New York')])

    This method is especially useful when you want to loop through both keys and values simultaneously:

    for key, value in person.items():
        print(f"{key}: {value}")

Other Useful Dictionary Methods:

  1. get(key, default_value=None)

    • Purpose: Returns the value for the specified key. If the key is not found, it returns None by default, or the default_value you provide. This is safer than directly using dictionary[key] because it avoids a KeyError if the key doesn't exist.
    • Example:
      print(person.get("name"))       # Output: Alice
      print(person.get("gender"))     # Output: None (key not found)
      print(person.get("gender", "Unavailable")) # Output: Unavailable
  2. update({key1: value1, key2: value2, ...})

    • Purpose: Updates the dictionary with elements from another dictionary object or from an iterable of key-value pairs. If a key already exists, its value is updated; otherwise, the new key-value pair is added.
    • Example:
      person.update({"email": "alice@example.com", "age": 27})
      print(person)
      # Output: {'name': 'Alice', 'age': 27, 'occupation': 'Engineer', 'city': 'New York', 'email': 'alice@example.com'}
  3. pop(key, default_value=None)

    • Purpose: Removes the item with the specified key and returns its value. If the key is not found, it raises a KeyError unless a default_value is provided.
    • Example:
      occupation = person.pop("occupation")
      print(f"Removed occupation: {occupation}") # Output: Removed occupation: Engineer
      print(person)
      # Output: {'name': 'Alice', 'age': 27, 'city': 'New York', 'email': 'alice@example.com'}
      
      # print(person.pop("hobbies")) # This would raise a KeyError
      print(person.pop("hobbies", "No hobbies key found")) # Output: No hobbies key found
  4. popitem()

    • Purpose: Removes and returns a (key, value) pair. In Python 3.7+, it removes the last item inserted.
    • Example:
      last_item = person.popitem()
      print(f"Removed last item: {last_item}") # Example: Removed last item: ('email', 'alice@example.com')
      print(person)

These methods make dictionaries very flexible and powerful for organizing and managing data. The keys(), values(), and items() methods are particularly useful for iterating over a dictionary's contents.

You've already put your knowledge to use by querying these methods in your Python history, which is excellent!

>>> print(person.keys())
dict_keys(['name', 'occupation', 'city'])
>>> print(person.values())
dict_values(['Alice', 'engineer', 'NY'])
>>> print(person.items())
dict_items([('name', 'Alice'), ('occupation', 'engineer'), ('city', 'NY')])

Keep exploring; you're doing great! Let me know if you'd like to try out any of these other methods.

0 Comments

no data
Be the first to share your comment!