In Python, there are mutable and inmutable data types. Mutable data types can be changed after it has been created. Inmutable data types cannot be changed after they have been created.

Are dictionaries mutable in Python?

Yes, dictionaries are mutable in Python.

With dictionaries, we can add and remove items easily, and also change existing items.

For example, let’s say we create the following dictionary.

d = {"a": 1, "b": 2, "c": 3}

We can easily make changes to this dictionary to prove that it is mutable.

For example, to add a key to a dictionary, we can do the following.

d = {"a": 1, "b": 2, "c": 3}

d["d"] = 4


{'a': 1, 'b': 2, 'c': 3, 'd': 4}

If you want to delete a key from a dictionary, you can use the del keyword.

d = {"a": 1, "b": 2, "c": 3}

del d["b"]


{'a': 1, 'c': 3}

To replace a value in a dictionary, you can access the key and change the value.

d = {"a": 1, "b": 2, "c": 3}

d["a"] = 0 


{'a': 0, 'b':2, 'c': 3}

All of these operations show that dictionaries are mutable in Python.

Other Examples of Mutable Data Types in Python

Some other data types which are mutable in Python include lists, sets and user-defined classes.

For example, with lists, we can add items to a list, remove items from lists, and easily change the items in a list.

One example of a data type which is inmutable is the tuple data type.

Tuples are inmutable because, after you’ve created it, you cannot add or remove items from the tuple or change the elements of a tuple.

Basically, if an object can be change over time, then it is mutable. If it cannot change, then it is inmutable.

Hopefully this article has been useful for you to learn that dictionaries are mutable and about mutable data types in Python.

Categorized in:


Last Update: March 22, 2024