Saturday 26 June, 2010

The mutability of Python Dictionaries


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


Python dictionary objects are mutable. That means, once created it can be modified later.


There are various ways in which the mutability of dictionaries in Python is useful, let's look at the following scenario

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


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.


This feature of Python was quite unaware to me, unless i encountered a bug in my application and the tracking lead me to this !!

No comments:

Post a Comment