Summary: In this tutorial, we will learn about the Python dictionary data structure. We will learn what it is, how can we create it, what operations can we perform on it, and will also look at the various methods that it supports.

Introduction to Python Dictionary

The dictionary data structure in Python is used to store an unordered collection of key-value pairs.

The dictionary in Python is like the map of Java and C++. It stores mappings of keys to values.

The following is an example of a Python dictionary:

>>> d = {'key1': 'value1', 'key2': 'value2'}
>>> print(type(d))
<class 'dict'>

The key and value of a pair can be of any primitive or user-defined type but each key in a dictionary should be unique.

The dictionary and list data structure are similar in terms of some properties like they both are:

  • mutable – we can modify the value for a key (but not the vice versa) in the dictionary.
  • dynamic – we can add or remove elements from the dictionary.

However, unlike the list, the dictionary is not indexed. We cannot access its items by position (via indexing) but via keys as follows:

>>> d = {2: 4, 3: 9, 4: 16}
>>> print(d[4])
16

How to create a dictionary in Python?

There are two ways using which we can create a dictionary in Python:

  1. Using curly braces ({})
  2. Using dict() constructor

To create a dictionary using {}, we have to write the key-value pairs separated by commas inside it.

>>> d = {'lang': 'Python', 'category': 'Programming'} 

To create a dictionary using the dict() constructor, pass the key-value pairs as keyword arguments to the constructor.

>>> d = dict(name='Python', num=25)
>>> print(d)
{'name': 'Python', 'num': 25}

The dict() constructor also accepts iterables such as a list. So, if we pass a list of tuples as a parameter, it will create a dictionary.

>>> d = dict([(1, 1), (2, 8), (3, 27), (4, 64)])
>>> print(d)
{1: 1, 2: 8, 3: 27, 4: 64}

The drawback of using dict() constructor is that the type of keys of the dictionary is always string.

Python Dictionary Operations

Like other data structures, there are various operations such as accessing items, iteration, adding and removing key-value pairs, modifying values of keys, etc., we can perform on a dictionary in Python. Let’s look at them one by one.

Accessing values

In Python, we can access the values of a dictionary via its keys. For this we can either use the square brackets ([]) or the get() method of the dictionary.

Accessing value using [] is very easy, we just have to mention the key inside it.

>>> d = {'name': 'AK', 'roll': 5}
>>> print(d['roll']
)
5

Similarly, using the get() method we can access the values as follows:

>>> d = {'id': 4365, 'password': '#%8fjmsb^&4'}
>>> print(d.get('id'))
4365

The difference between these two methods of accessing values is that the [] throws an error if the key doesn’t exist in the dictionary whereas the get() method returns None for the same.

>>> d = {'model': 'iPhoneX', 'price': '$999', 'headphoneIncluded': False}
>>> print(d.get('mode'))
None
>>> print(d['mode'])
KeyError: 'mode'

We can also make the get() method returns a default value for the non-existing keys by passing the default value as the second parameter.

>>> d = {1: 'Tokyo', 2: 'Beijing'}
>>> print(d.get(5))
None
>>> print(d.get(5, 'Delhi'))
Delhi

Modifying Existing Values

By accessing the key using the [] operator and specifying a new value for it, we can modify the value of an existing key in the dictionary.

>>> d = {'name': 'Pencil Programmer', 'profession': 'Programming'}
>>> d['profession'] = 'Coding'
>>> print(d)
{'name': 'Pencil Programmer', 'profession': 'Coding'}

Alternatively, we can use the update() method to update the dictionary from a dictionary object or the keyword arguments as follows:

>>> d = {'name': 'John', 'profession': 'student'}
>>> d.update({'profession': 'IT Professional'})
>>> print(d)
{'name': 'John', 'profession': 'IT Professional'}
>>> d.update(profession = 'Manager')
>>> print(d)
{'name': 'John', 'profession': 'Manager'}

Add or Remove key-value pairs

Because the dictionary in Python is dynamic, we can easily add new key-value pairs to it.

When we assign a value to a key using the [] operator (square bracket) and the key does not exist in the dictionary, it is added to the dictionary object.

>>> d = {2: 4, 3: 9, 4: 16}
>>> d[5] = 25
>>> print(d)
{2: 4, 3: 9, 4: 16, 5: 25}

Similarly, if we need to remove the existing key-value pairs from the dictionary, we can use the Python del statement on the key as follows:

>>> del d[3]
>>> print(d)
{2: 4, 4: 16, 5: 25}

Another way to remove a key-value pair from the dictionary is by using the pop() method.

The pop() method accepts the key as a parameter and returns its corresponding value after removing it from the dictionary.

>>> d = {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> r = d.pop(3)
>>> print(r)
9
>>> print(d)
{1: 1, 2: 4, 4: 16, 5: 25}

Iterate through key-value pairs

When we need to process each key-value pair of the given dictionary one by one, we must iterate through them using the for loop in Python.

One way to do this is to iterate through the items() of the dictionary. The items() method of the dictionary returns an iterable list that contains key-value pairs in tuples.

>>> d = {'full_name': 'Jack Smith', 'age': 29, 'location': 'UK'}
>>> for key, value in d.items():
...     print(key,' : ', value)
... 
full_name  :  Jack Smith
age  :  29
location  :  UK

Refer to this post to know different ways of iterating through a dictionary in Python.

Nested Dictionary

A nested dictionary is a dictionary inside a dictionary. Python allows to nest the dictionary data structure inside of the other one.

For example, in the following dictionary, the dog key has a value of type dictionary:

>>> animal = {'breath': 'true', 'dog': {'legs': 4} }
>>> print(animal)
{'breath': 'true', 'dog': {'legs': 4}}
>>> print(animal['dog'])
{'legs': 4}

This type of dictionary is useful in representing a hierarchical data structure in Python.

Dictionary Methods

The dictionary data structure in Python comes with a number of inbuilt functions. These functions are useful in performing certain tasks such as updating or deleting items from the dictionary.

Some of the methods names and their corresponding task are as follows:

  • update({‘key’: ‘new_value’}) – Update the current ‘value’ of ‘key’ with ‘new_value’.
  • get(‘key’) – returns the value corresponding to the ‘key’.
  • items() – returns dictionary as list of tuples.
  • pop(‘key’) – removes the key:value pair from the dictionary.
  • keys() – returns list of keys present in the dictionary.
  • values() – returns list of values present in the dictionary.
  • clear() – empties the dictionary.

Summary

The dictionary data structure stores the mapping of key-value pairs in Python.

It is created using the curly brackets ({}) and can contain only unique keys.

The dictionary in Python is mutable, dynamic but not ordered. We can access the values by keys can perform various operations such as iteration, data manipulation, etc.

Leave a Reply