Most Frequently asked dictionary Interview Questions and Answers

author image Hirely
at 04 Jan, 2025

Question: How to add, update, or delete a key-value pair in a Python dictionary?

Answer:

In Python, dictionaries are mutable data structures that allow you to store key-value pairs. Here’s how you can add, update, or delete key-value pairs in a dictionary:

  1. Adding a Key-Value Pair:

    • You can add a new key-value pair by simply assigning a value to a new key.
    my_dict = {"apple": 1, "banana": 2}
    my_dict["cherry"] = 3  # Adds a new key "cherry" with value 3
    print(my_dict)  # Output: {'apple': 1, 'banana': 2, 'cherry': 3}
  2. Updating an Existing Key-Value Pair:

    • To update the value of an existing key, you can assign a new value to that key.
    my_dict["apple"] = 4  # Updates the value of "apple" to 4
    print(my_dict)  # Output: {'apple': 4, 'banana': 2, 'cherry': 3}
  3. Deleting a Key-Value Pair:

    • You can remove a key-value pair using the del statement or the pop() method:
      • del removes the key-value pair directly:
      del my_dict["banana"]  # Removes the key "banana"
      print(my_dict)  # Output: {'apple': 4, 'cherry': 3}
      • pop() removes the key and returns its value:
      value = my_dict.pop("cherry")  # Removes the key "cherry" and stores its value in 'value'
      print(value)  # Output: 3
      print(my_dict)  # Output: {'apple': 4}

These operations are efficient with a time complexity of O(1) for adding, updating, and deleting key-value pairs in a dictionary.

Question: What happens if you try to access a key that does not exist in a Python dictionary?

Answer:

If you try to access a key that does not exist in a Python dictionary, a KeyError will be raised.

For example:

my_dict = {"apple": 1, "banana": 2}
print(my_dict["cherry"])  # This will raise a KeyError because "cherry" does not exist in the dictionary

Output:

KeyError: 'cherry'

To avoid this error, you can use one of the following methods:

  1. Using get() method: The get() method returns None (or a specified default value) instead of raising an error if the key does not exist.

    value = my_dict.get("cherry")  # Returns None since "cherry" is not in the dictionary
    print(value)  # Output: None
    
    value = my_dict.get("cherry", "Not Found")  # Returns the default value if the key doesn't exist
    print(value)  # Output: Not Found
  2. Using in keyword: You can check if a key exists in the dictionary before accessing it.

    if "cherry" in my_dict:
        print(my_dict["cherry"])
    else:
        print("Key not found")
    # Output: Key not found

These methods provide ways to handle the absence of a key gracefully without causing a runtime error.

Question: How can you check if a key exists in a Python dictionary?

Answer:

In Python, you can check if a key exists in a dictionary using the in keyword or the get() method. Here’s how you can do it:

  1. Using the in keyword: The in keyword checks if a key is present in the dictionary. It returns True if the key exists, otherwise False.

    my_dict = {"apple": 1, "banana": 2}
    if "apple" in my_dict:
        print("apple exists in the dictionary")
    else:
        print("apple does not exist in the dictionary")
    # Output: apple exists in the dictionary
  2. Using the get() method: The get() method returns the value associated with the key if it exists, and None (or a default value) if the key does not exist.

    value = my_dict.get("banana")  # Returns 2 if the key exists
    if value is not None:
        print("banana exists in the dictionary")
    else:
        print("banana does not exist in the dictionary")
    # Output: banana exists in the dictionary
  3. Using dict.keys() method: You can check the keys explicitly by converting the dictionary keys to a list or using keys() method.

    if "cherry" in my_dict.keys():
        print("cherry exists in the dictionary")
    else:
        print("cherry does not exist in the dictionary")
    # Output: cherry does not exist in the dictionary

These methods allow you to handle cases where the key may or may not be present in the dictionary without raising an error.

Question: What is the purpose of the get() method in a Python dictionary?

Answer:

The get() method in a Python dictionary is used to access the value associated with a specific key. It is particularly useful for safely retrieving a value without raising a KeyError if the key does not exist in the dictionary.

The syntax is:

value = dictionary.get(key, default)
  • key: The key whose value you want to retrieve.
  • default (optional): The value to return if the key does not exist in the dictionary. If not provided, it returns None by default.

Key Benefits:

  1. Avoids KeyError: If the key doesn’t exist, instead of raising an error, get() will return None (or the specified default value).
  2. Provides a default value: You can specify a default return value if the key is not found, which makes your code more robust.

Examples:

  1. Accessing an existing key:

    my_dict = {"apple": 1, "banana": 2}
    value = my_dict.get("apple")
    print(value)  # Output: 1
  2. Accessing a non-existing key:

    value = my_dict.get("cherry")
    print(value)  # Output: None (since "cherry" is not in the dictionary)
  3. Specifying a default value:

    value = my_dict.get("cherry", "Not Found")
    print(value)  # Output: Not Found (since "cherry" is not in the dictionary)

Summary:

The get() method is useful when you want to access a value in a dictionary but don’t want to handle errors in case the key is missing. It provides a safer and more flexible way to handle missing keys, especially when working with dynamic or uncertain data.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as dictionary interview questions, dictionary interview experiences, and details about various dictionary job positions. Click here to check it out.

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now