Dictionary is an unordered, mutable, dynamic size collection datatype in Python. Dictionary stores elements in key-value pairs, where elements are indexed by keys. Dictionary keys can only be of immutable datatype but values can be of any datatype. From Python version 3.7 and later, dictionaries maintain insertion order.
In this article, we will learn about various methods to add elements in dictionary.
Add elements in Dictionary
Dictionary being a mutable datatype, we can perform add (append), update (change), delete (remove) operations on the dictionary. We can use key index
and update()
method to add elements in dictionary.
Lets see various scenarios to add elements (key-value pairs) in the dictionary.
Add element using key
Dictionary elements are indexed by keys, this is similar to list where list elements were indexed by their positions. We can use key index to add or update elements in the dictionary. Syntax for adding element using key index –
dictionary[key] = value
- Add key-value – If given
key
does not exists in thedictionary
, then that key-value will be added into the dictionary. - Update key-value – If given
key
already exists in thedictionary
, then that key-value will be updated into the dictionary. Dictionary will not store duplicate keys.
# add element using key
print("add element using key")
shbytes_dict = {"c1": "Python", "c2": "NumPy", "c3": "Pandas", "c4": "Java"}
print(shbytes_dict) # print dictionary before add or update key-value
shbytes_dict["c5"] = "Machine Learning" # add key-value pair, c5 key does not exists
print(shbytes_dict) # print dictionary after add key-value
shbytes_dict["c4"] = "AI" # update key-value pair, c4 key already exists
print(shbytes_dict) # print dictionary after update key-value
In this program, we have defined a dictionary shbytes_dict
. Using shbytes_dict["c5"]
will add a key-value pair, because c5
key does not exists in the dictionary. Using shbytes_dict["c4"]
will update the existing key value, because c4
key already exists in the dictionary.
Program Output
add element using key
{'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'Java'}
{'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'Java', 'c5': 'Machine Learning'} # print dictionary after add key-value
{'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'AI', 'c5': 'Machine Learning'} # print dictionary after update key-value
From the program output, using a new key 'c5': 'Machine Learning'
was added into the dictionary. Using the already existing key 'c4': 'AI'
, value of c4
was updated.
update()
method
Add element using Similar to key index, we can use update()
method to add or update elements into the dictionary. Syntax for update()
method:
dictionary.update({key_1: value_1, ...key_n: value_n})
# add element using update method
print("add element using update method")
courses = {1: "Python", 2: "NumPy", 3: "Pandas", 4: "Java"}
print(courses) # print dictionary before add or update key-value
courses.update({5: "Data Science"}) # add key-value pair, 5 key does not exists
print(courses) # print dictionary after add key-value
courses.update({4: "AI"}) # update key-value pair, 4 key already exists
print(courses) # print dictionary after update key-value
Here we have defined a dictionary courses
. Using courses.update({5: "Data Science"})
will add a key-value pair, because 5
key does not exists in the dictionary. Using courses.update({4: "AI"})
will update the existing key value, because 4
key already exists in the dictionary.
Program Output
add element using update method
{1: 'Python', 2: 'NumPy', 3: 'Pandas', 4: 'Java'}
{1: 'Python', 2: 'NumPy', 3: 'Pandas', 4: 'Java', 5: 'Data Science'} # print dictionary after add key-value
{1: 'Python', 2: 'NumPy', 3: 'Pandas', 4: 'AI', 5: 'Data Science'} # print dictionary after update key-value
From the program output, using a new key 5: 'Data Science'
was added into the dictionary. Using the already existing key 4: 'AI'
, value of key 4
was updated.
update()
method
Add multiple elements using Using update()
method we can add multiple key-value pairs simultaneously into the dictionary.
# add & update multiple elements using update method
print("add & update multiple elements using update method")
courses = {1: "Python", 2: "NumPy", 3: "Pandas"}
print(courses)
courses.update(dict({4: "Data Science", 5: "ML"})) # add multiple key-value pairs
print(courses) # print dictionary after add key-value
courses.update(dict({2: "Machine Learning", 3: "AI"})) # update multiple key-value pairs
print(courses) # print dictionary after update key-value
Here we are adding and updating multiple key-value pairs simultaneously. Using courses.update(dict({4: "Data Science", 5: "ML"}))
will add two key-value pairs, because keys 4 & 5 does not exists in the dictionary. Using courses.update(dict({2: "Machine Learning", 3: "AI"}))
will update the existing key value, because keys 2 & 3 already exists in the dictionary.
Program Output
add & update multiple elements using update method
{1: 'Python', 2: 'NumPy', 3: 'Pandas'}
{1: 'Python', 2: 'NumPy', 3: 'Pandas', 4: 'Data Science', 5: 'ML'} # print dictionary after add key-value
{1: 'Python', 2: 'Machine Learning', 3: 'AI', 4: 'Data Science', 5: 'ML'} # print dictionary after update key-value
From the program output, using a new keys 4: 'Data Science', 5: 'ML'
were added into the dictionary. Using the already existing keys 2: 'Machine Learning', 3: 'AI'
, value of key 2 & 3
were updated.
Add collection element
Dictionary element keys must be unique and of immutable types (e.g., strings, numbers, and tuples). But values can be of any datatype.
# add collection element
print("add collection element")
shbytes_dict = {1: "Python"}
print(shbytes_dict)
shbytes_dict["courses"] = "AWS", "Azure" # add element with tuple value
print(shbytes_dict)
Here we are adding value added for a key is of tuple datatype.
Program Output
add collection element
{1: 'Python'}
{1: 'Python', 'courses': ('AWS', 'Azure')}
From the program output, a new key-value pair 'courses': ('AWS', 'Azure')
was added into the dictionary, where value is of tuple datatype.
Add nested key-value to dictionary
We can add key-value pair, where the value of a key is another dictionary. We can refer these dictionaries as nested dictionaries. Value can be of any datatype like a list, tuple, set, number, string, boolean etc.
# add nested Key value to a dictionary
print("add nested Key value to a dictionary")
shbytes_dict = {}
print(shbytes_dict)
shbytes_dict["courses"] = {"AWS", "Azure", "Python"} # add element with set value
shbytes_dict["programs"] = ["online", "learning"] # add element with list value
print(shbytes_dict)
Here, we are adding set and a list as value to keys.
Program Output
add nested Key value to a dictionary
{}
{'courses': {'Azure', 'AWS', 'Python'}, 'programs': ['online', 'learning']} # added list and set as value
Summary
In this article we learn about various scenarios to add and update elements into the dictionary. Following scenarios were explored:
Code – Github Repository
All code snippets and programs for this article and for Python tutorial, can be accessed from Github repository – Comments and Docstring in Python.
Python Topics
Interview Questions & Answers
Q: How can we merge two dictionaries in Python?
In Python 3.5 and above, we can merge two dictionaries using the update()
method or the **
unpacking operator.
- Using
**
unpacking (Python 3.5+) – This creates a new dictionary with merged key-value pairs - Using
|
operator (Python 3.9+) – This creates a new dictionary with merged key-value pairs - Using
update()
method – This updates the first dictionary with merged key-value pairs
courses_dict = {"c1": "Python", "c2": "NumPy", "c3": "Pandas", "c4": "Java"}
numbers_dict = {1: 2, 2: 4, 3: 9, 4: 16}
updated_dict_1 = {**courses_dict, **numbers_dict} # Creates new dictionary with merged key-value pairs
print(updated_dict_1)
# {'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'Java', 1: 2, 2: 4, 3: 9, 4: 16}
updated_dict_2 = courses_dict | numbers_dict # Creates new dictionary with merged key-value pairs
print(updated_dict_2)
# {'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'Java', 1: 2, 2: 4, 3: 9, 4: 16}
courses_dict.update(numbers_dict) # Update courses_dict with merged key-value pairs
print(courses_dict)
# {'c1': 'Python', 'c2': 'NumPy', 'c3': 'Pandas', 'c4': 'Java', 1: 2, 2: 4, 3: 9, 4: 16}
Q: What is the time complexity to merge two dictionaries in Python?
Time complexity of merging two dictionaries is O(n), where n is the total number of elements in both dictionaries. This is because each element in the second dictionary must be inserted into the first, which on average takes constant time per insertion.
Q: How to add elements to a dictionary, only if the key does not already exist?
There are two ways we can add elements to a dictionary, only if the key does not already exist.
- Before adding a new key-value pair, we can check if the key already exists using the
in
operator. - We can use the
setdefault()
method, which only adds the key-value pair if the key does not already exist.
courses_dict = {1: "Python", 2: "NumPy", 3: "Pandas", 4: "Java"}
courses_dict.setdefault(2, "Power BI") # does not add, as key 2 already exists
courses_dict.setdefault(5, "Power BI") # Add key 5 with value
print(courses_dict)
# Elements in courses_dict => {1: 'Python', 2: 'NumPy', 3: 'Pandas', 4: 'Java', 5: 'Power BI'}
Q: How to add elements to a dictionary in a thread-safe manner?
In Python, in multi-threaded environment, we can use locks from the threading
module to ensure that dictionary updates are thread-safe.
import threading
courses_dict = {}
lock = threading.Lock()
def add_to_dictionary(key, value):
with lock:
courses_dict[key] = value
add_to_dictionary(1, "Python")
- Import
threading
module - Declare
lock = threading.Lock()
- Take lock
with lock
on the dictionary update block
Q: How can we efficiently add a large number of elements to a dictionary?
To add large number of elements to a dictionary, we can use update()
method with another dictionary or iterable of key-value pairs. update()
method is optimized for bulk updates and can be significantly faster than adding elements one by one.