Python Dictionary
Python dictionary is yet another unordered collection of elements. The difference between Python dictionary and other unordered Python data types such 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 Data Science Course to get ahead in your career!
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 are 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!
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:
- 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
- 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.
If you are looking for upskilling yourself in python you can join our best Python training in Bangalore and learn from the industry expert.
Iterate a Dictionary in Python
To iterate through a dictionary, we can use 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
Get 100% Hike!
Master Most in Demand Skills Now!
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 Python
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 represent 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 bypassing 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
Sort Dictionary by value in Python
To sort a dictionary by value in python, there is a built-in sorted()function. It can easily sort dictionaries by a key. It takes three arguments: object, key, and reverse, but the object is the only mandatorily required argument. If you do not give the optional key and reverse parameters, the dictionary will automatically be sorted in ascending order.
order = {‘coffee’:43,‘tea’: 67,‘biscuit’: 51,‘croissants’:83}
s_order = sorted(order.items(),key=lambda x:x[1], reverse=True)
for i in s_order:
print(i[0],i[1])
The output will be
croissants 83
tea 67
biscuit 51
coffee 43
Update Dictionary
Python has an update() method that can insert specified items into a dictionary. The specified item can be a dictionary itself, or iterable objects with key-value pairs.
car = {“brand”: “Volkswagen”, “model”: “Polo”, “year”: 2014}
car.update({“colour”: “Black”})
print(car)
The output will be
{'brand': 'Volkswagen', 'model': 'Polo', 'year': 2014, 'colour': 'Black'}
Nested Dictionary in Python
A dictionary can also contain multiple dictionaries. This is called a nested dictionary.
employees = {1: {'name': 'Jack', 'age': '28', 'sex': 'Male'},
2: {'name': 'Joan', 'age': '25', 'sex': 'Female'}}
print(employees[1]['name'])
print(employees[1]['age'])
print(employees[1]['sex'])
The output will be
Jack
28
Male
Ordered Dictionary in Python
There is a dictionary subclass, OrderedDict, which remembers and preserves the order in which the keys were inserted. A regular dict doesn’t do that and when you iterate, the values will be given in an arbitrary order.
from collections import OrderedDict
print("Here is a Dict:")
d = {}
d['a'] = 1
d['b'] = 2
d['c'] = 3
d['d'] = 4
for key, value in d.items():
print(key, value)
print("This is an Ordered Dict:")
od = OrderedDict()
od['a'] = 1
od['b'] = 2
od['c'] = 3
od['d'] = 4
for key, value in od.items():
print(key, value)
The output will be
Here is a Dict:
a 1
c 3
b 2
d 4
Here is an Ordered Dict:
a 1
b 2
c 3
d 4
Dictionary Comprehension in Python
Dictionary Comprehension is a concept that can substitute lambda functions and for loops. All dictionary comprehension can be written with for loops but all for loops can not be written as dictionary comprehensions
keys = ['a','b','c','d','e']
values = [1,2,3,4,5]
dict1 = { k:v for (k,v) in zip(keys, values)}
print (dict1)
The output will be
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
Convert list to Dictionary in Python
The list can be converted into a dictionary using dictionary comprehension.
student = ["Jack", "Aaron", "Philip", "Ben"]
student_dictionary = { stu : "Passed" for stu in student }
print(student_dictionary)
The output will be
{'Jack': 'Passed', 'Aaron': 'Passed', 'Philip': 'Passed', 'Ben': 'Passed'}
Common Python Dictionary Methods
Let’s understand some common dictionary methods by going through the following table:
Method |
Description |
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 the end of this module in Python Tutorial. Here, we talked about how to create a dictionary in Python, how to access Items, perform operations in the dictionary in Python, looping Through a dictionary, Adding Items to a dictionary, Removing Items from a dictionary, and delete the whole dictionary, 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 Data Science tutorial.
Further, check out how to get certified via our Python training course. You can also go through this free Python Developer Interview Questions blog so that you know what sort of questions are asked during interviews.