Dictionary Datatype in Python

Python dictionary is yet another unordered collection of elements. The difference between Python Dictionary and other unordered datatype in Python such as Sets lies in the fact that unlike Sets, Dictionary contains key and values rather than just an element.
Like lists, Python Dictionaries can also be changed and modified but unlike lists, the values in dictionaries are accessed using keys and not their positions. All the keys in dictionary are mapped to their respective values. The value can be of any datatype in Python.
We are going to learn all that we need to know about Dictionary Datatype in Python in order to get started with it. Following is the list of topics that we will be covering in case you need to jump to a specific one.

So, without any further delay let’s get started.

Create a dictionary

While creating a dictionary in Python, there are some rules that we need to keep in mind such as follows:

  • The keys are separated from their respective values by a colon (:) between them and each key-value pair is separated using commas (,).
  • All the items are enclosed in curly braces.
  • While the values in dictionaries may repeat themselves but keys are always unique.
  • The value can be of any datatype but the keys should be of immutable datatype that is, strings, numbers or tuples.

Following code block is an example to show how to create and print a dictionary.

dict1 ={“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print (dict1)

Output:

{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921}

You can also declare an empty dictionary as shown below

dict2 = {}

We can also create dictionary by using an inbuilt method dict () as shown in the following example:

dict3 = dict([(1, ‘Intellipaat’), (2,’Python’)])

Access items in Dictionary

As discussed above, to access elements in Dictionary we have to use keys instead of the indexes. Now there are two different ways of using keys to access elements as shown below:
1. Using the key inside square brackets like we used to use index inside the square brackets.
Example:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(dict1[‘year’])

Output:

1921

2. Using the get() method and passing the key as parameter inside this method.
Example:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print (dict1.get(‘year’))

Output:

1921

Operations in Dictionary

There are various operations in Dictionary and in this section, we will learn about some of the most basic and most frequently used operations such as iterating through a dictionary, adding new elements, updating already existing elements, removing some specific elements along with deleting the whole dictionary at once and many more.

Loop through a dictionary

To iterate through a dictionary, we can use a for loop. Let’s say we want to print all the elements in dictionary ten we will use for loop as shown in the below example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
for i in cubes:
print(cubes[i])

Output:

1
8
21
64
125

Adding items in a Dictionary

Dictionary is a mutable datatype that means that we can add new elements or change the value of existing elements in Python Dictionary. While adding or changing an existing value we have to use keys. If the key already exists then the value gets updated if the key does not exist then new key value pair is generated.
Example:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(dict1)
#creating new key-value pair
dict1[‘product’] = “Tote Handbag”
print(dict1)
#updating existing value
dict1[‘Industry’] = “Fashion and Luxury”
print(dict2)

Output:

{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921}
{‘Brand’: ‘gucci’, ‘Industry’: ‘fashion’, ‘year’: 1921, ‘product’: ‘Tote Handbag’}
{‘Brand’: ‘gucci’, ‘Industry’: ‘Fashion and Luxury’, ‘year’: 1921, ‘product’: ‘Tote Handbag’}

Removing items from the Dictionary and deleting the whole dictionary

There are various ways which we can use to remove elements from dictionary such as using pop() method, popitem() method or by using del keyword. Let’s understand all of these individually with the help of examples.

Removing elements using pop() method:

We use pop() method to remove a particular element from dictionary by providing the key of the element as a parameter to the method as shown in the example below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
print(cubes.pop(4))
print(cubes)

Output

64
{1: 1, 2: 8, 3: 21, 5: 125}

Removing elements using popitem() method:

We can use popitem() method to remove any randomly picked element as shown in the example below.

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
print(cubes.popitem())
print(cubes)
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}

 

Removing items using del keyword in Dictionary:

We use del keyword to delete an item as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
del cubes[5]
print (cubes)

Output:

{1: 1, 2: 8, 3: 21, 4: 64}

Deleting the all the elements using clear() method

We can use clear() method and it will clear out or delete all the elements from the dictionary at once as shown in the following example:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
cubes.clear()
print(cubes)

Output:

{}

As discussed above, curly braces with nothing inside represents an empty dictionary. Since clear() methods deletes all the elements at once, the output of printing the dictionary after using clear() method on it is an empty dictionary, that is, {}.

Deleting the whole dictionary

As we have already seen that we can use the del keyword to delete a particular item by passing the key of that particular item, but that is not all we can do using del keyword. We can also delete the whole dictionary at once using the del keyword as shown in the example below:

cubes = {1:1, 2:8, 3:21, 4:64, 5:125}
cubes.del()
print(cubes)

Output:

Traceback (most recent call last):
File “”, line 1, in
NameError: name ‘cubes’ is not defined

Dictionary Length

To check the length of the dictionary, that is, to check how many key-value pairs are there in a dictionary, we use the len() method as shown in the example below:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
print(len(dict1))

Output:

3

Check all the keys

To find a particular key or to check if a particular key exists in a Dictionary, we use the if statement and “in” keyword as shown in the example below:

dict1 = {“Brand”:”gucci”,”Industry”:”fashion”,”year”:1921}
if “industry” in dict1:
print (“Yes, ‘Industry’ is one of the Keyword in dictionary named dict1”)

Output:

Yes, ‘Industry’ is one of the Keyword in dictionary named dict1

Common Dictionary methods

Let’s understand some common dictionary methods by going through the following table

MethodDescription
clear()It removes all the elements from the dictionary
copy()It returns a copy of the dictionary
fromkeys()It returns a dictionary with the specified keys and values
get()It returns the value of the specified key
items()It returns a list containing a tuple for each key-value pair
keys()It returns a list containing the dictionary’s keys
pop()It removes the element with the specified key
popitem()It removes the last inserted (key, value) pair
setdefault()It returns the value of the specified key.
update()It updates the dictionary with the specified key-value pairs
values()It returns a list of all the values in the dictionary

With this we come to an end of this module, the next module highlights the operators in Python, see you there!

Leave a Reply

Your email address will not be published. Required fields are marked *

Solve : *
6 + 2 =