I have been working with Python dictionaries and came to learn quite a lot about it. Well first of all, Python dictionaries are a mapping object types. Said that, it means we can create a mapping and store it in dictionary objects.
It goes on something like this
>> my_dict = {‘food’ : ‘something that we eat’, ‘car’ : ‘something that we drive’}
>>> my_dict[‘food’]
‘something that we eat’
>>> my_dict[‘car’]
‘something that we drive’
]]>
Python dictionary objects are mutable. That means, once created it can be modified later.
>> my_dict[‘food’] = ‘pizza’
>>> my_dict
{‘food’ : ‘pizza’, ‘car’ : ‘something that we drive’}
]]>
There are various ways in which the mutability of dictionaries in Python is useful, let’s look at the following scenario
>> his_dict = my_dict
>>> his_dict
{‘food’ : ‘pizza’, ‘car’ : ‘something that we drive’}
>>> his_dict[‘food’] = ‘cookie’
>>> his_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’}
>>> my_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’}
]]>
As can be seen, changing the value of his_dict has changed the value of my_dict too. This phenomenon can be extended to n number of assigned dictionaries
>> her_dict = his_dict
>>> her_dict[‘party_place’] = ‘howzzat’
>>> her_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
>>> his_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
>>> my_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
]]>
Now this behavior is exploited in various situations, but there can be cases when this behavior is not desired. In those cases, we need to use the copy method. The copy method creates a shallow copy of the dictionary.
>> her_copy = his_dict.copy()
>>> her_copy
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
>>> her_copy[‘food’] = ‘Indian’
>>> her_copy
{‘food’: ‘Indian’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
>>> his_dict
{‘food’: ‘cookie’, ‘car’: ‘something that we drive’, ‘party_place’: ‘howzzat’}
>>>
]]>
This feature of Python was quite unaware to me, unless i encountered a bug in my application and the tracking lead me to this !!