Saturday, February 17, 2018

Copying Dictionaries in Python

Copying Dictionaries

Let's say we have a dictionary as below:
>>> aDict_1 = {"name": "Jason", "role": "BA", "loc": "Finland"}

The line below will create an alias of the already existing dictionary, but not a copy.

>>> aDict_2 = aDict_1
>>>
>>> aDict_2
{'name': 'Jason', 'role': 'BA', 'loc': 'Finland'}
>>>

>>> id(aDict_1)
5103712
>>> id(aDict_2)
5103712




So, both the dictionaries point to the same address in the memory.

Let's check what happens when we update aDict_2:

>>> aDict_2["role"] = "Business Analyst"
>>> aDict_2
{'name': 'Jason', 'role': 'Business Analyst', 'loc': 'Finland'}

So, aDict_2 is updated fine. How about aDict_1:

>>> aDict_1
{'name': 'Jason', 'role': 'Business Analyst', 'loc': 'Finland'}


Ah, so we see a problem here, and this is not what we wanted.

There are two ways to solve this problem. We can create a shallow copy or a deep copy of the dictionary.

So, let's say our new dictionary is:

>>> new_dict = {"org":"newTek", "resources": [{'name': 'Guptil', 'role': 'System Analyst', 'loc': 'England'}]}

>>> shallow_dict = new_dict.copy()  # shallow copy
>>> shallow_dict
{'org': 'newTek', 'resources': [{'name': 'Guptil', 'role': 'System Analyst', 'loc': 'England'}]}


Now, let's try to update few values in the shallow_dict and see if it effects the new_dict-

>>> shallow_dict["org"] = "newTech" # updated
>>> shallow_dict
{'org': 'newTech', 'resources': [{'name': 'Guptil', 'role': 'System Analyst', 'loc': 'England'}]}
>>>
>>> new_dict
{'org': 'newTek', 'resources': [{'name': 'Guptil', 'role': 'System Analyst', 'loc': 'England'}]}


So, this did solve our problem. But wait, let's check one more thing. We'll update the role of the resource from System Analyst to Sr. System Analyst in the shallow_dict

>>> shallow_dict["resources"][0]["role"]
'System Analyst'
>>> shallow_dict["resources"][0]["role"] = "Sr. System Analyst"
>>>
>>> shallow_dict
{'org': 'newTech', 'resources': [{'name': 'Guptil', 'role': 'Sr. System Analyst'
, 'loc': 'England'}]}
>>> new_dict
{'org': 'newTek', 'resources': [{'name': 'Guptil', 'role': 'Sr. System Analyst',
 'loc': 'England'}]}



Here, the role got updated in the new_dict this time, something we didn't wanted. So we make a deepcopy using the copy module,

>>> import copy
>>> copied_dict = copy.deepcopy(new_dict)
>>> copied_dict["resources"][0]["role"]
'Sr. System Analyst'
>>> copied_dict["resources"][0]["role"]  = "Program Manager"
>>>
>>> copied_dict
{'org': 'newTek', 'resources': [{'name': 'Guptil', 'role': 'Program Manager', 'loc': 'England'}]}
>>> new_dict
{'org': 'newTek', 'resources': [{'name': 'Guptil', 'role': 'Sr. System Analyst',
 'loc': 'England'}]}


Looks like we solved the problem.

Thanks for reading.



No comments:

Post a Comment

Copying Dictionaries in Python

Copying Dictionaries Let's say we have a dictionary as below: >>> aDict_1 = {"name": "Jason", ...