Open In App

Python program to change values in a Dictionary

Improve
Improve
Like Article
Like
Save
Share
Report

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




# declaring dictionary
dict = {'hari': 1, 'dita': 2}
  
# original dictionary
print("initial dictionary-", dict)
  
# changing the key value from  2 to 4
dict['dita'] = 4
  
# dictionary after update
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




# declaring dictionary
dict1 = {'hari': 1, 'dita': 2}
  
# original dictionary
print("initial dictionary-", dict1)
  
# list of values which will replace the values of dict1
list1 = [3, 5]
  
# this preserves the keys and modifies the values
dict1 = dict(zip(list(dict1.keys()), list1))
  
# modified dictionary
print("dictionary after modification-", dict1)


Output:

initial dictionary- {‘hari’: 1, ‘dita’: 2} 

dictionary after modification- {‘hari’: 3, ‘dita’: 5}



Last Updated : 08 Dec, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads