Open In App

Python Dictionary Pass by Value/Reference

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, dictionaries are passed by reference, not by value. Since dictionaries are mutable, passing them to a function means the original dictionary can be modified.

If we want to avoid changes to the original, we can create a copy before passing it. Understanding this behavior is key to managing data effectively in Python.

Pass by Reference in Python Dictionaries

Since dictionaries are mutable items, when we pass a dictionary to a function, the characteristic works with the original dictionary, no longer a duplicate of it.

Any modification made to the dictionary within the characteristic will have an effect on the original dictionary.

Python
def fun(a):
    a["newkey"] = "new_val"  # update the dictionary

d = {"key": "old_val"} 
fun(d) # passing dictionery as a reference

print(d)

Output
{'key': 'old_val', 'newkey': 'new_val'}

Explanation :

  • This function fun modifies the dictionary passed to it by adding a new key-value pair .
  • Since dictionaries are passed by reference, the changes are reflected in the original dictionary and the updated dictionary is printed.

Pass by Value in Python Dictionaries

Since dictionaries are mutable, passing one to a function modifies the original. To avoid this, create a copy using .copy() or dict(), so the original remains unchanged.

Python
def fun(a):
    a["newkey"] = "new_val"  # Modify the dictionary
d1 = {"key": "old_val"}
d2 = d1.copy()  # Create a copy of the dictionary
fun(d2)
print(d1)       
print(d2)  

Output
{'key': 'old_val'}
{'key': 'old_val', 'newkey': 'new_val'}

Explanation:

  • This function fun modifies the dictionary passed to it by adding "newkey": "new_val", but the original d remains unchanged.
  • A copy of d1 is created using .copy(), and the modification occurs on the copy, leaving d unchanged and d2 updated.

Next Article
Article Tags :
Practice Tags :

Similar Reads