Q:

Python program to change the dictionary items

belongs to collection: Python Dictionary Programs

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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}

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python Dictionary Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Loop through a dictionary in Python... >>
<< Python program for removing elements from a dictio...