Python program to change the dictionary items

Here, we are going to learn how to change the dictionary items in Python?
Submitted by Shivang Yadav, on March 24, 2021

A dictionary contains the pair of the keys & values (represents key : value), a dictionary is created by providing the elements within the curly braces ({}), separated by the commas. 

Here, we are going to learn the different ways to change the dictionary items,

  1. Direct (simple) way to change the dictionary items
  2. Using the update() method to change the dictionary items

1) Direct (simple) way to change the dictionary items

The simple way is to change the dictionary items – assign the new value by referring to the key of the dictionary.

Syntax:

dictionary_name[key] = new_value

Program:

# Python program to change the dictionary items

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# updating the values of name and age
dict_a['name'] = 'Shivang Yadav'
dict_a['age'] = 23

# printing the dictionary 
# after changing the values
print("Updated Dictionary \'dict_a\' is...")
print(dict_a)

Output:

Dictionary 'dict_a' is...
{'name': 'Amit', 'id': 101, 'age': 21}
Updated Dictionary 'dict_a' is...
{'name': 'Shivang Yadav', 'id': 101, 'age': 23}

2) Using the update() method to change the dictionary items

The update() method can also be used to change the dictionary items. The update method accepts the key: value pair.

Syntax:

dictionary_name.update({key:value})

Program:

# Python program to change the dictionary items
# using the update() method

# creating the dictionary
dict_a = {'id' : 101, 'name' : 'Amit', 'age': 21}

# printing the dictionary
print("Dictionary \'dict_a\' is...")
print(dict_a)

# updating the values of name and age
# using the update() method
dict_a.update({'name': 'Shivang Yadav'})
dict_a.update({'age': 23})

# printing the dictionary 
# after changing the values
print("Updated Dictionary \'dict_a\' is...")
print(dict_a)

Output:

Dictionary 'dict_a' is...
{'id': 101, 'name': 'Amit', 'age': 21}
Updated Dictionary 'dict_a' is...
{'id': 101, 'name': 'Shivang Yadav', 'age': 23}

Python Dictionary Programs »



Related Programs




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.