Dictionary in Python

Python dictionary is yet another unordered collection of elements. The difference between Python dictionary and other unordered Python data types such as sets lies in the fact that unlike sets, a dictionary contains keys and values rather than just elements.

Like lists, Python dictionaries can also be changed and modified, but unlike Python lists the values in dictionaries are accessed using keys and not by their positions. All the keys in a dictionary are mapped to their respective values. The value can be of any data type in Python.

Learn more about Python from this Python for Data Science Course to get ahead in your career!

Watch this video on Python:

Python Dictionary Dictionary in Python Python dictionary is yet another unordered collection of elements. The difference between Python dictionary and other unordered Python data types such as sets lies in the fact that unlike sets, a dictionary contains keys and values rather than just elements. Like lists, Python dictionaries can also be

We are going to learn all that we need to know about the dictionary data type in Python in order to get started with it. Following is the list of topics that we will be covering in this module.

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

Create a Dictionary in Python

While creating a dictionary in Python, there are some rules that we need to keep in mind 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 items are enclosed in curly braces.
  • While the values in dictionaries may repeat, the keys are always unique.
  • The value can be of any data type, but the keys should be of immutable data type, that is, (Python Strings, Python Numbers, Python Tuples).

Here is a few Python dictionary examples:

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


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

We can also declare an empty dictionary as shown below:

dict2 = {}

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

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

Interested in learning Python? Enroll in our Python Course in London now!

Watch this Python Pygame Tutorial Video for Beginners:

Python Dictionary Dictionary in Python Python dictionary is yet another unordered collection of elements. The difference between Python dictionary and other unordered Python data types such as sets lies in the fact that unlike sets, a dictionary contains keys and values rather than just elements. Like lists, Python dictionaries can also be

Access Items in Dictionary in Python

As discussed above, to access elements in a dictionary, we have to use keys instead of 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 the index inside square brackets.

Example:

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


Output:
1921
  1. Using the get() method and passing the key as a parameter inside this method.

Example:

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


Output:
1921

Operations in Dictionary in Python

There are various operations in a 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 in Python

To iterate through a dictionary, we can use the Python for loop. Let’s say, we want to print all elements in a dictionary, then 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

Add Items to a Dictionary in Python

Python dictionary is a mutable data type that means that we can add new elements or change the value of the existing elements in it. 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 a 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’}

Remove Items from a Dictionary and Delete the Whole Dictionary in Pyhton

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

Remove elements using the pop() method:

We use the pop() Python Function to remove a particular element from a 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}

Remove Elements Using the popitem() Method:

We can use the 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)


Output:
(5, 125)
{1: 1, 2: 8, 3: 21, 4: 64}

Kick-start your career in Python with the perfect Python Course in New York now!

Remove Items Using the del Keyword in a Dictionary:

We use the 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}

Delete All Elements Using the Clear() Method:

We can use the clear() method, and it will clear out or delete all elements from a 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 the clear() method deletes all elements at once, the output of printing the dictionary after using the clear() method on it is an empty dictionary, that is, {}.

Deleting the Whole Dictionary:

As we have already seen, 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 the del keyword. We can also delete a 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

Python 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

Go for the most professional Python Course Online in Toronto  for a stellar career now!

Checking All Keys in a Dictionary in Python

To find a particular key or to check if a particular key exists in a dictionary, we use the Python if statement and the ‘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 Python Dictionary Methods

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

MethodDescription
clear()It removes all elements from a dictionary.
copy()It returns a copy of a dictionary.
fromkeys()It returns a dictionary with the specified keys and values.
get()It returns the value of a 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 an element with a specified key.
popitem()It removes the last inserted (key, value) pair.
setdefault()It returns the value of a specified key.
update()It updates a dictionary with the specified key–value pairs.
values()It returns a list of all values in a dictionary.

With this, we come to an end of this module in Python Tutorial. Here, we talked about how to create a dictionary in Python, how to access Items in dictionary in Python, performing operations in dictionary in Python, looping Through a dictionary in Python, Adding Items to a dictionary in Python, Removing Items from a dictionary and deleting the whole dictionary in Python, Python dictionary length, checking all keys in a dictionary in Python, and also discussed some common Python Dictionary Methods. Now, if you are interested in knowing why Python is the most preferred language for Data Science, you can go through this blog on Python for Data Science.
Further, check out how to get certified via our Python training course. You can also go through this free Python Interview Questions blog, so that you know what sort of questions are asked during interviews.

Leave a Reply

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

Solve : *
10 + 6 =