Modify the values of t
he dictionary keys
We can modify the values of the existing dictionary keys using the following two ways.
Using key name: We can directly assign new values by using its key name. The key name will be the existing
one and we can mention the new value.
Using update() method: We can use the update method by passing the key-value pair to change the value.
Here the key name will be the existing one, and the value to be updated will be new.
Example
person = {"name": "Jessa", "country": "USA"}
# updating the country name
person["country"] = "Canada"
# print the updated country
print(person['country'])
# Output 'Canada'
# updating the country name using update() method
person.update({"country": "USA"})
# print the updated country
print(person['country'])
# Output 'USA'
Run
Removing items from the dictionary
There are several methods to remove items from the dictionary. Whether we want to remove the single item or the
last inserted item or delete the entire dictionary, we can choose the method to be used.
Use the following dictionary methods to remove keys from a dictionary.
Method Description
Return and removes the item with the key and
pop(key[,d]
return its value. If the key is not found, it
)
raises KeyError.
Return and removes the last inserted item from the
popitem() dictionary. If the dictionary is empty, it
raises KeyError.
Method Description
The del keyword will delete the item with the key
del key
that is passed
Removes all items from the dictionary. Empty the
clear()
dictionary
del
Delete the entire dictionary
dict_name
Example
person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50,
'height': 6}
# Remove last inserted item from the dictionary
deleted_item = person.popitem()
print(deleted_item) # output ('height', 6)
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA', 'telephone': 1178, 'weight': 50}
# Remove key 'telephone' from the dictionary
deleted_item = person.pop('telephone')
print(deleted_item) # output 1178
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA', 'weight': 50}
# delete key 'weight'
del person['weight']
# display updated dictionary
print(person)
# Output {'name': 'Jessa', 'country': 'USA'}
# remove all item (key-values) from dict
person.clear()
# display updated dictionary
print(person) # {}
# Delete the entire dictionary
del person
Run
Checking if a key exists
In order to check whether a particular key exists in a dictionary, we can use the keys() method and in operator.
We can use the in operator to check whether the key is present in the list of keys returned by
the keys() method.
In this method, we can just check whether our key is present in the list of keys that will be returned from
the keys() method.
Let’s check whether the ‘country’ key exists and prints its value if found.
person = {'name': 'Jessa', 'country': 'USA', 'telephone': 1178}
# Get the list of keys and check if 'country' key is present
key_name = 'country'
if key_name in person.keys():
print("country name is", person[key_name])
else:
print("Key not found")
# Output country name is USA
Run
Join two dictionary
We can add two dictionaries using the update() method or unpacking arbitrary keywords operator **. Let us see
each one with an example.
Using update() method
In this method, the dictionary to be added will be passed as the argument to the update() method and the updated
dictionary will have items of both the dictionaries.
Let’s see how to merge the second dictionary into the first dictionary
Example
dict1 = {'Jessa': 70, 'Arul': 80, 'Emma': 55}
dict2 = {'Kelly': 68, 'Harry': 50, 'Olivia': 66}
# copy second dictionary into first dictionary
dict1.update(dict2)
# printing the updated dictionary
print(dict1)
# output {'Jessa': 70, 'Arul': 80, 'Emma': 55, 'Kelly': 68, 'Harry': 50,
'Olivia': 66}
Run
As seen in the above example the items of both the dictionaries have been updated and the dict1 will have the
items from both the dictionaries.
Using **kwargs to unpack
We can unpack any number of dictionary and add their contents to another dictionary using **kwargs. In this
way, we can add multiple length arguments to one dictionary in a single statement.
student_dict1 = {'Aadya': 1, 'Arul': 2, }
student_dict2 = {'Harry': 5, 'Olivia': 6}
student_dict3 = {'Nancy': 7, 'Perry': 9}
# join three dictionaries
student_dict = {**student_dict1, **student_dict2, **student_dict3}
# printing the final Merged dictionary
print(student_dict)
# Output {'Aadya': 1, 'Arul': 2, 'Harry': 5, 'Olivia': 6, 'Nancy': 7,
'Perry': 9}
Run
As seen in the above example the values of all the dictionaries have been merged into one.
Join two dictionaries having few items in common
Note: One thing to note here is that if both the dictionaries have a common key then the first dictionary value will
be overridden with the second dictionary value.
Example
dict1 = {'Jessa': 70, 'Arul': 80, 'Emma': 55}
dict2 = {'Kelly': 68, 'Harry': 50, 'Emma': 66}
# join two dictionaries with some common items
dict1.update(dict2)
# printing the updated dictionary
print(dict1['Emma'])
# Output 66
Run
As mentioned in the case of the same key in two dictionaries the latest one will override the old one.
In the above example, both the dictionaries have the key ‘Emma’ So the value of the second dictionary is used in
the final merged dictionary dict1.
Copy a Dictionary
We can create a copy of a dictionary using the following two ways
Using copy() method.
Using the dict() constructor
dict1 = {'Jessa': 70, 'Emma': 55}
# Copy dictionary using copy() method
dict2 = dict1.copy()
# printing the new dictionary
print(dict2)
# output {'Jessa': 70, 'Emma': 55}
# Copy dictionary using dict() constructor
dict3 = dict(dict1)
print(dict3)
# output {'Jessa': 70, 'Emma': 55}
# Copy dictionary using the output of items() methods
dict4 = dict(dict1.items())
print(dict4)
# output {'Jessa': 70, 'Emma': 55}
Run
Copy using the assignment operator
We can simply use the '=' operator to create a copy.
Note: When you set dict2 = dict1, you are making them refer to the same dict object, so when you modify
one of them, all references associated with that object reflect the current state of the object. So don’t use the
assignment operator to copy the dictionary instead use the copy() method.
Example
dict1 = {'Jessa': 70, 'Emma': 55}
# Copy dictionary using assignment = operator
dict2 = dict1
# modify dict2
dict2.update({'Jessa': 90})
print(dict2)
# Output {'Jessa': 90, 'Emma': 55}
print(dict1)
# Output {'Jessa': 90, 'Emma': 55}
Run
Nested dictionary
Nested dictionaries are dictionaries that have one or more dictionaries as their members. It is a collection of many
dictionaries in one dictionary.
Let us see an example of creating a nested dictionary ‘Address’ inside a ‘person’ dictionary.
Example
# address dictionary to store person address
address = {"state": "Texas", 'city': 'Houston'}
# dictionary to store person details with address as a nested dictionary
person = {'name': 'Jessa', 'company': 'Google', 'address': address}
# Display dictionary
print("person:", person)
# Get nested dictionary key 'city'
print("City:", person['address']['city'])
# Iterating outer dictionary
print("Person details")
for key, value in person.items():
if key == 'address':
# Iterating through nested dictionary
print("Person Address")
for nested_key, nested_value in value.items():
print(nested_key, ':', nested_value)
else:
print(key, ':', value)
Run
Output
person: {'name': 'Jessa', 'company': 'Google', 'address': {'state': 'Texas',
'city': 'Houston'}}
City: Houston
Person details
name: Jessa
company: Google
Person Address
state: Texas
city : Houston