Modify The Values of The Dictionary Keys Day 2
Modify The Values of The Dictionary Keys Day 2
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
Run
Method Description
raises KeyError.
Method Description
The del keyword will delete the item with the key
del key
that is passed
del
Delete the entire dictionary
dict_name
Example
Run
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.
Run
Let’s see how to merge the second dictionary into the first dictionary
Example
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.
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}
Run
As seen in the above example the values of all the dictionaries have been merged into one.
Example
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
Run
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
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
# Display dictionary
print("person:", person)
# Get nested dictionary key 'city'
print("City:", person['address']['city'])
Run
Output
City: Houston
Person details
name: Jessa
company: Google
Person Address
state: Texas
city : Houston