Most Frequently asked dictionary Interview Questions (2024)

author image Hirely
at 04 Jan, 2025

Question: How can you iterate over a dictionary in Python?

Answer:

In Python, you can iterate over a dictionary in several ways, depending on what parts of the dictionary you want to access (keys, values, or key-value pairs). Here are the most common methods to iterate over a dictionary:

1. Iterating over Keys:

By default, iterating over a dictionary directly will give you the keys.

my_dict = {"apple": 1, "banana": 2, "cherry": 3}

for key in my_dict:
    print(key)
# Output:
# apple
# banana
# cherry

You can also explicitly iterate over the dictionary’s keys using the keys() method:

for key in my_dict.keys():
    print(key)
# Output:
# apple
# banana
# cherry

2. Iterating over Values:

To iterate over the values in the dictionary, use the values() method.

for value in my_dict.values():
    print(value)
# Output:
# 1
# 2
# 3

3. Iterating over Key-Value Pairs:

You can use the items() method to iterate over both keys and their corresponding values.

for key, value in my_dict.items():
    print(key, value)
# Output:
# apple 1
# banana 2
# cherry 3

4. Using Dictionary Comprehension:

You can also use dictionary comprehension to iterate and transform the dictionary into a new dictionary or list.

# Example: Creating a new dictionary with values squared
squared_values = {key: value**2 for key, value in my_dict.items()}
print(squared_values)
# Output: {'apple': 1, 'banana': 4, 'cherry': 9}

Summary:

  • for key in my_dict:: Iterates over the keys.
  • for key in my_dict.keys():: Explicitly iterates over the keys.
  • for value in my_dict.values():: Iterates over the values.
  • for key, value in my_dict.items():: Iterates over both keys and values.

These methods provide flexibility to access and manipulate the dictionary contents during iteration.

Question: What is the difference between keys(), values(), and items() methods in a Python dictionary?

Answer:

The keys(), values(), and items() methods in a Python dictionary provide different views of the dictionary’s data. Here’s how each method works and how they differ:

1. keys() Method:

  • Purpose: Returns a view object that displays all the keys in the dictionary.
  • Return Type: A dict_keys view object (which behaves like a set).
  • Usage: When you only need to access the keys of the dictionary.
  • Example:
    my_dict = {"apple": 1, "banana": 2, "cherry": 3}
    keys = my_dict.keys()
    print(keys)  # Output: dict_keys(['apple', 'banana', 'cherry'])
    for key in keys:
        print(key)
    # Output:
    # apple
    # banana
    # cherry

2. values() Method:

  • Purpose: Returns a view object that displays all the values in the dictionary.
  • Return Type: A dict_values view object (which behaves like a collection).
  • Usage: When you only need to access the values of the dictionary.
  • Example:
    values = my_dict.values()
    print(values)  # Output: dict_values([1, 2, 3])
    for value in values:
        print(value)
    # Output:
    # 1
    # 2
    # 3

3. items() Method:

  • Purpose: Returns a view object that displays all the key-value pairs in the dictionary as tuples.
  • Return Type: A dict_items view object (which behaves like a set of tuples).
  • Usage: When you need to access both keys and values simultaneously.
  • Example:
    items = my_dict.items()
    print(items)  # Output: dict_items([('apple', 1), ('banana', 2), ('cherry', 3)])
    for key, value in items:
        print(f"{key}: {value}")
    # Output:
    # apple: 1
    # banana: 2
    # cherry: 3

Key Differences:

  1. keys(): Provides a view of just the keys of the dictionary.
  2. values(): Provides a view of just the values in the dictionary.
  3. items(): Provides a view of both keys and their corresponding values as pairs (tuples).

Summary:

  • keys(): Use when you need only the keys.
  • values(): Use when you need only the values.
  • items(): Use when you need both keys and values together in a tuple format.

Question: How can you merge two dictionaries in Python?

Answer:

In Python, there are several ways to merge two dictionaries. Here are the most common methods:

1. Using the update() Method:

  • The update() method adds the key-value pairs from one dictionary to another, modifying the original dictionary.
  • If a key already exists in the dictionary, its value is updated to the value from the other dictionary.

Example:

dict1 = {"apple": 1, "banana": 2}
dict2 = {"cherry": 3, "banana": 4}

dict1.update(dict2)  # Merges dict2 into dict1
print(dict1)  # Output: {'apple': 1, 'banana': 4, 'cherry': 3}
  • Note: The update() method modifies the first dictionary (dict1 in this case) and does not create a new one.

2. Using Dictionary Unpacking (Python 3.5+):

  • In Python 3.5 and later, you can merge dictionaries using the ** unpacking operator. This creates a new dictionary that contains the contents of both dictionaries.
  • If a key exists in both dictionaries, the value from the second dictionary will overwrite the value from the first dictionary.

Example:

dict1 = {"apple": 1, "banana": 2}
dict2 = {"cherry": 3, "banana": 4}

merged_dict = {**dict1, **dict2}  # Merges dict1 and dict2 into a new dictionary
print(merged_dict)  # Output: {'apple': 1, 'banana': 4, 'cherry': 3}
  • This method creates a new dictionary, so the original dictionaries are not modified.

3. Using the | (Pipe) Operator (Python 3.9+):

  • In Python 3.9 and later, you can use the | operator to merge dictionaries. This returns a new dictionary that combines both dictionaries.
  • If a key is present in both dictionaries, the value from the second dictionary will overwrite the value from the first.

Example:

dict1 = {"apple": 1, "banana": 2}
dict2 = {"cherry": 3, "banana": 4}

merged_dict = dict1 | dict2  # Merges dict1 and dict2 into a new dictionary
print(merged_dict)  # Output: {'apple': 1, 'banana': 4, 'cherry': 3}
  • This method is concise and creates a new dictionary without modifying the originals.

4. Using a Loop (Manual Merging):

  • If you need more control over how the dictionaries are merged, you can manually iterate over the dictionaries and combine them using a loop.

Example:

dict1 = {"apple": 1, "banana": 2}
dict2 = {"cherry": 3, "banana": 4}

merged_dict = dict1.copy()  # Start with a copy of dict1 to avoid modifying it
for key, value in dict2.items():
    merged_dict[key] = value  # Add or update key-value pairs from dict2
print(merged_dict)  # Output: {'apple': 1, 'banana': 4, 'cherry': 3}

Key Differences:

  • update(): Modifies the first dictionary in place.
  • Dictionary unpacking (**): Creates a new dictionary, keeping the originals intact (available in Python 3.5+).
  • | (Pipe) operator: Introduced in Python 3.9, it is an intuitive way to merge dictionaries and creates a new dictionary.
  • Manual Looping: Provides full control, but is more verbose.

Summary:

  • Use update() if you want to modify the first dictionary.
  • Use dictionary unpacking (**) or the | operator if you want to create a new dictionary by merging the two.
  • For more complex merging strategies, you can loop through the dictionaries manually.

Question: How do you handle default values when accessing dictionary keys in Python?

Answer:

In Python, there are several ways to handle default values when accessing dictionary keys, particularly when the key may not exist in the dictionary. Here are the most common methods:

1. Using the get() Method:

  • The get() method allows you to specify a default value to return if the key is not found in the dictionary. If no default value is provided, it returns None by default.

Syntax:

value = dictionary.get(key, default_value)
  • key: The key whose value you want to retrieve.
  • default_value (optional): The value returned if the key does not exist. If not specified, it defaults to None.

Example:

my_dict = {"apple": 1, "banana": 2}
value = my_dict.get("cherry", 0)  # Default value is 0 if "cherry" is not found
print(value)  # Output: 0
  • In this example, since “cherry” is not a key in the dictionary, 0 is returned as the default value.

2. Using the setdefault() Method:

  • The setdefault() method retrieves the value for a given key. If the key is not found, it inserts the key into the dictionary with the specified default value and returns the default value.

Syntax:

value = dictionary.setdefault(key, default_value)
  • key: The key whose value you want to retrieve.
  • default_value: The value to insert if the key does not exist.

Example:

my_dict = {"apple": 1, "banana": 2}
value = my_dict.setdefault("cherry", 0)  # "cherry" is not present, so it will be added with value 0
print(value)  # Output: 0
print(my_dict)  # Output: {'apple': 1, 'banana': 2, 'cherry': 0}
  • In this case, "cherry" is added to my_dict with the default value 0.

3. Using the in Keyword to Check Existence:

  • Before accessing the value, you can check if the key exists in the dictionary using the in keyword. If the key exists, you can access the value, otherwise, you can handle the default value logic yourself.

Example:

my_dict = {"apple": 1, "banana": 2}
if "cherry" in my_dict:
    value = my_dict["cherry"]
else:
    value = 0  # Default value if "cherry" is not found
print(value)  # Output: 0
  • This method gives you complete control over how you handle missing keys, but it requires more code.

4. Using collections.defaultdict:

  • If you often need to assign a default value when accessing dictionary keys, you can use defaultdict from the collections module. A defaultdict automatically assigns a default value when a key is accessed that doesn’t exist.

Example:

from collections import defaultdict

my_dict = defaultdict(int)  # Default value is 0 for any missing key
my_dict["apple"] = 1
print(my_dict["banana"])  # Output: 0 (default value for missing key)
  • In this example, int is used as the default factory function, so missing keys are assigned a value of 0. You can specify any callable to set a different default value.

Summary:

  • get(): Use to safely access keys with an optional default value if the key doesn’t exist.
  • setdefault(): Use to access a key, and if it doesn’t exist, add it with a default value.
  • in keyword: Use to check if a key exists before accessing it, allowing for custom handling of missing keys.
  • defaultdict: Use for dictionaries where you want automatic handling of default values for missing keys.

Each of these methods helps handle default values in a way that prevents errors when accessing missing keys in a dictionary.

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