How to Add Elements to a Dictionary in Python?

To add elements to a dictionary, we do not have a specific method; instead, we use a syntax that helps us add a new key-value pair to the dictionary.

You can add elements to a dictionary by directly assigning a value to a new key using the following syntax.

Syntax:

dictionary_name["new_key"] = value

Example:

student = {"name": "Kriss Moris", "age": 21}

student["Subject"] = "Python"

print(student)

Output:

{'name': 'Kriss Moris', 'age': 21, 'Subject': 'Python'}

There is also another method i.e update() to add elements to a dictionary in Python, aside from the direct assignment method.

The update() method allows you to add multiple key-value pairs at once. If a key already exists, its value will be updated.

 Syntax:

dictionary_name.update({key1: value1, key2: value2, ...})

Example:

student = {"name": "Kriss Moris", "age": 21}

student.update({"Subject": "Pytohn", "Start_Year": 2025})

print(student)

Output:

{'name': 'Kriss Moris', 'age': 21, 'Subject': 'Pytohn', 'Start_Year': 2025}

 


13+ interview questions related to adding elements in a dictionary in Python

Question 1. What is the basic syntax to add a new key-value pair to a dictionary?

Answer: The basic syntax to add a new key-value pair is:

 Example:

dictionary_name["new_key"] = value

 

 Question 2. How can you add multiple key-value pairs to a dictionary at once?

Answer: You can use the update() method to add multiple key-value pairs.

 Example:

dictionary_name.update({key1: value1, key2: value2})

 

 Question 3. What happens if you add a key that already exists in the dictionary?

Answer: If the key already exists, its value will be updated to the new value.

 Example:

student = {"name": "Alice", "age": 21}
student["age"] = 22
print(student) 

Output:

{'name': 'Alice', 'age': 22}

 

 Question 4. How do you add an element using the setdefault() method?

Answer:  The setdefault() method adds a key with a specified value if the key does not already exist.

Syntax:

 

dictionary_name.setdefault(key, default_value)

 Example:

student = {"name": "Alice"}
student.setdefault("age", 21)
print(student) 

Output:

{'name': 'Alice', 'age': 21}

 

 Question 5. Can you add elements to a nested dictionary? If so, how?

Answer: Yes, you can add elements to a nested dictionary using the same syntax.

 Example:

student = {"name": "Alice", "details": {}}
student["details"]["age"] = 21
print(student)  

Output:

{'name': 'Alice', 'details': {'age': 21}}

 

 Question 6. How do you add elements to a dictionary using dictionary comprehension?

Answer: You can create a new dictionary that includes existing and new key-value pairs using dictionary comprehension.

 Example:

student = {"name": "Alice"}
student = {**student, "age": 21}
print(student)

Output:

{'name': 'Alice', 'age': 21}

 

 Question 7. How can you merge two dictionaries together?

Answer: You can merge dictionaries using the update() method or the | operator (Python 3.9+).

 Example:

dict1 = {"name": "Alice"}
dict2 = {"age": 21}
dict1.update(dict2)
print(dict1) 

Output:

{'name': 'Alice', 'age': 21}

 

 Question 8. What will happen if you try to add an immutable type as a key in a dictionary?

Answer: Dictionaries only allow immutable types as keys (e.g., strings, numbers, tuples). If you use a mutable type (e.g., list), it will raise a TypeError.

 Example:

try:
    my_dict = {[1, 2, 3]: "value"}
except TypeError as e:
    print(e) 

Output:

unhashable type: 'list'

 

 Question 9. How can you add elements to a dictionary inside a loop?

Answer: You can add elements to a dictionary within a loop by iterating over a collection.

 Example:

student = {}
for i in range(3):
    student[f"subject_{i}"] = f"Subject {i+1}"
print(student)  

Output:

{'subject_0': 'Subject 1', 'subject_1': 'Subject 2', 'subject_2': 'Subject 3'}

 

 Question 10. Can you use a function to add elements to a dictionary?

Answer: Yes, you can define a function to add elements to a dictionary.

 Example:

def add_student_info(student_dict, key, value):
    student_dict[key] = value

student = {}
add_student_info(student, "name", "Alice")
add_student_info(student, "age", 21)
print(student)  

Output:

{'name': 'Alice', 'age': 21}

 

 Question 11. How can you add a key-value pair only if the key does not exist?

Answer: You can check if the key exists before adding it.

 Example:

student = {"name": "Alice"}
if "age" not in student:
    student["age"] = 21
print(student)

Output:

{'name': 'Alice', 'age': 21}

 

 Question 12. How can you add elements to a dictionary from a list of tuples?

Answer: You can use a loop or the dict() constructor to convert a list of tuples into a dictionary.

 Example:

data = [("name", "Alice"), ("age", 21)]
student = dict(data)
print(student) 

Output:

{'name': 'Alice', 'age': 21}

 

 Question 13. How can you dynamically add elements to a dictionary based on user input?

Answer: You can use input() to take user input and add it to a dictionary.

 Example:

student = {}
key = input("Enter key: ")
value = input("Enter value: ")
student[key] = value
print(student)

Output:

Enter key: 12
Enter value: 23
{'12': '23'}

 

 Question 14. How can you use collections.defaultdict to add elements?

Answer: Using defaultdict, you can specify a default type for dictionary values, which can simplify adding elements.

 Example:

from collections import defaultdict

student = defaultdict(list)
student["subjects"].append("Math")
print(student) 

Output:

defaultdict(<class 'list'>, {'subjects': ['Math']})

 

Leave a comment

You must be logged in to post a comment.

0 Comments