Python program to change values in a Dictionary
Last Updated :
08 Dec, 2020
Given a dictionary in Python, the task is to write a Python program to change the value in one of the key-value pairs. This article discusses mechanisms to do this effectively.
Examples:
Input: {'hari': 1, 'dita': 2}
Output: {'hari': 1, 'dita': 4}
Input: {'hari': 1, 'dita': 2}
Output: {'hari': 3, 'dita': 5}
Changing Values of a Dictionary
Method 1
In this we refer to the key of the value to be changed and supply it with a new value.
Example:
Python3
dict = { 'hari' : 1 , 'dita' : 2 }
print ( "initial dictionary-" , dict )
dict [ 'dita' ] = 4
print ( "dictionary after modification-" , dict )
|
Output:
initial dictionary- {‘hari’: 1, ‘dita’: 2}
dictionary after modification- {‘hari’: 1, ‘dita’: 4}
Method 2:
In this method we use zip() function, which aggregates the iterable and combines them into a tuple form.
Example:
Python3
dict1 = { 'hari' : 1 , 'dita' : 2 }
print ( "initial dictionary-" , dict1)
list1 = [ 3 , 5 ]
dict1 = dict ( zip ( list (dict1.keys()), list1))
print ( "dictionary after modification-" , dict1)
|
Output:
initial dictionary- {‘hari’: 1, ‘dita’: 2}
dictionary after modification- {‘hari’: 3, ‘dita’: 5}
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...