Dictionary is mutable in python

A Dictionary is mutable in Python. What does that mean? In short, it means we can use the concept of CRUD with a dictionary.

Let’s clarify the concept a little bit.

Actually it’s simple. CRUD represents four words – C for Create, R for retrieve, U for update, and D for delete.

In the coming examples we’ll use the first three. 

In short we’ll create an empty dictionary, adding elements to a dictionary, retrieving elements from a dictionary, and modifying a dictionary by changing an existing value.

If you are a beginner in Python, please read the previous section where we have discussed Set and Dictionary.

Firstly, the Dictionary is a built-in Python Data Structure that we can change.

As long as we think of data structure in Python, any dictionary may be similar in spirit to List, Set, and Tuples.


If you are a complete beginner your journey to learn TensorFlow might start from here.

For the TensorFlow beginners we have a dedicated category – TensorFlow for Beginners.

But besides that, you may need to learn several other machine learning and data science libraries.

As a result, you may check these categories as well – NumPy, Pandas, Matplotlib.

However, without learning Python, you cannot learn the usages of these libraries. Why? Because they all use Python as the Programming language.

Therefore please learn Python at the very beginning and start learning TensorFlow.

And, finally please check our Mathematics, Discrete Mathematics and Data Structures categories specially. We have tried to discuss from basic to intermediate level so that you can pick up the core ideas of TensorFlow.


But actually there is a big difference that makes a dictionary very special.

Whether a Dictionary is mutable or not, that is not the point of concern. The Python list is also mutable.

The main point is a dictionary is not indexed by a sequence of numbers but indexed based on keys.

Each key should be unique and must point to an associated value. 

That’s why we can also say that a python dictionary is like an associative array.

In short, it consists of a key with an associated value .

At the same time, a Python dictionary is an ordered collection of items. 

As a result, we treat each item of a dictionary as a key and value pair.

When we know the key, we can easily retrieve value.

We can create a Python Dictionary quite easily. 

However, we can create a dictionary using two ways.

Let’s see an example. Please read the comments. That will also give you more information.

'''
keys must be of immutable types, that means it should be represented by
string, number or tuple with immutable elements and must be unique.
'''

# an empty dictionary is possible
dictionary_example = {}
print(dictionary_example)

# a dictionary with integer keys
dictionary_example = {1: 'Mars', 2: 'Moon'}
print(dictionary_example)

# a dictionary with mixed keys
dictionary_example = {'name': 'John', 1 : [2, 4, 3]}
print(dictionary_example)

# we can create python dictionary using dict() method
dictionary_example = dict({1 :'Mars', 2 :'Moon'})
print(dictionary_example)

# from sequence having each item as a pair
dictionary_example = dict([(1,'Mars'), (2,'Moon')])

print(dictionary_example)
{}
{1: 'Mars', 2: 'Moon'}
{'name': 'John', 1: [2, 4, 3]}
{1: 'Mars', 2: 'Moon'}
{1: 'Mars', 2: 'Moon'}

When we say ‘pair’, we mean a key and its associated value. Right? 

However, if there is no pair, and we are still pressing to retrieve that value, it will give us an error.

Here is an example.

# use [] for retrieving elements
dictionary_example = {'name': 'Jon', 'age': 33}

# Output: John
print(dictionary_example['name'])

# Output: 33
print(dictionary_example.get('age'))

# If we try to access keys which doesn't exist, it throws error
# Output None
print(dictionary_example.get('address'))

# The Error
# KeyError
print(dictionary_example['address'])
Jon
33
None
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-2-659be6e7dab3> in <module>
     13 
     14 # KeyError
---> 15 print(dictionary_example['address'])

KeyError: 'address'

While creating a dictionary, please remember one thing. 

We can use any data type as values, but we cannot use a mutable data type like list as the key.

Keys must be of immutable type, that is of string, number or tuple with immutable elements.

In addition, keys must be unique.

Certainly, we can also create a dictionary using the built-in dict() function.

Some may prefer to use the curly braces ‘{ }’. 

However, it’s up to the developers to choose its own way.

Retrieving any value in a Python dictionary is quite easy. 

We have seen it above.

Changing and adding Dictionary elements is also easy. 

Let’s see a few examples.

# We can change and add to Dictionary Elements
# first an example
dictionary_examples = {'name': 'Json', 'age': 32}
print(dictionary_examples)

# Let's update value of the age
dictionary_examples['age'] = 27
print(dictionary_examples)


# Let's add another item to the dictionary
dictionary_examples['address'] = 'Moon'
print(dictionary_examples)

Here is the output of the changed value.

{'name': 'Json', 'age': 32}
{'name': 'Json', 'age': 27}
{'name': 'Json', 'age': 27, 'address': 'Moon'}

In the next section, we will find how we can remove or delete a value. We’ll also learn a few built in dictionary functions.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

Flutter, Dart, Python and TensorFlow

C, C++ Java, and Game Development

Twitter

Comments

One response to “Dictionary is mutable in python”

  1. […] However, in the previous section we have seen how a python dictionary behaves as a mutable data structure. […]

Leave a Reply