In this python tutorial you will master all about Python Dictionary with examples; how to create a dictionary, how to modify a python dictionary, how to remove and standard operations on dictionaries. Besides these, we will learn about the methods to manipulate dictionaries.
A dictionary is a collection of items that are unordered and mutable. Dictionary items are usually represented as Key: Value pairs which are enclosed in curly braces{}. Each Key: Value pair is separated using commas. In a nutshell, a dictionary is a key-value mapping as visualized below.
A dictionary in python can be defined by enclosing comma-separated key-value pairs inside curly braces {}. Another way to create a dictionary is through the built-in dict()
function.
<dict_name> = {
<key>:<value>,
<key>:<value>,
.
.
<key>:<value>
}
Empty Dictionary: Python dictionary with zero items.
emp_dict ={}
print(type(emp_dict))
Output:
<class 'dict'>
Homogeneous Dictionary: A Dictionary with keys of the same immutable datatype.
int_dict={1:'Odd',2:'Even'}
print(int_dict)
Output:
{1: 'Odd', 2: 'Even'}
Mixed Dictionary: A Dictionary with keys of the different immutable datatypes.
mix_dict={1:'Student','name':'Tom','Marks':[45,46,47,48,50 ]}
print(mix_dict)
Output:
{1: 'Student', 'name': 'Tom', 'Marks': [45, 46, 47, 48, 50]}
So far we have discussed various types of dictionaries and their creation. Another possible way to create a dictionary is using a function called dict().
fn_dict = dict({'Name':'John','Age':30})
print(fn_dict)
Output:
{'Name': 'John', 'Age': 30}
Two important factors in a python dictionary are Keys and Values. Their properties are listed below.
fn_dict = dict({'Name':'John','Age':30 ,'Name':'Charles'})
print(fn_dict)
Output:
{'Name': 'Charles', 'Age': 30}
Example:shows error when key is a list
D = {['odd']:(1,3,5,7,9)}
print(D)
Output:
D = {['odd']:[1,3,5,7,9]} TypeError: unhashable type: 'list'
D = {'odd':[1,3,5,7,9]}
print(D)
Output:
{'odd': [1, 3, 5, 7, 9]}
In Python, a dictionary containing another dictionary is referred to as Nested Dictionary. Nesting can be done to any level without any restriction. This can be visualized for better understanding.
University= {
'UN_Name':'Oxford',
'Stud':{ 'St1_Name':'Tom','St2_Name':'Becky' }
}
print(University)
Output:
{'UN_Name': 'Oxford', 'Stud': {'St1_Name': 'Tom', 'St2_Name': 'Becky'}}
We know that a dictionary is an unordered collection of key: value
pairs. Even though they appear as how they were defined, when it comes to accessing, numerical indexing does not work. This is because python interprets the numerical value as the key instead of index. So then how can we access values from a dictionary?
Dictionary uses keys to retrieve values from a dictionary. To access values we use the same square brackets with Keys inside rather than indices. We can also use the get() method to accomplish the same.
To understand let’s examine the below example.
mix_dict={1:'Student','name':'Tom','Marks':[45,46,47,48,50 ]}
print('mix_dict[1] = ',mix_dict[1])
print("mix_dict['name'] = ",mix_dict['name'])
print("mix_dict['Marks'] = ", mix_dict.get('Marks')
Output:
mix_dict[1] = Student mix_dict['name'] = Tom mix_dict['Marks'] = [45, 46, 47, 48, 50]
Now suppose you try to access a value with a key that is not defined in the dictionary. What will happen?
Obviously, an exception will be the result. If we refer to a key that is not present in the dictionary, the interpreter raises a KeyError
. This occurs only when we use square [] brackets to access value. The get()
method returns None
as the output.
D= { 'A':'Apple','B':'Banana'}
print(D.get('C'))
print(D['C'])
Output:
None print(D['C']) KeyError: 'C'
D={
'D1':{2:4,3:9},
'D2':{4:64,5:125}
}
print(D['D1'])
print(D['D2'])
print(D['D1'][3])
print(D['D2'][5])
Output:
{2: 4, 3: 9} {4: 64, 5: 125} 9 125
The mutable behavior of a dictionary makes it possible to modify the dictionary either by adding individual or group of entries or by replacing the existing value. Three ways of adding entries to a dictionary is listed below.
adding single entries to an empty dictionary
Student ={}
Student[' First_Name']='Charles'
Student['Last_Name'] = 'Smith'
print("\n Dictionary after adding two entries one at a time :",Student)
Output:
Dictionary after adding two entries one at a time : {' First_Name': 'Charles', 'Last_Name': 'Smith'}
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith'}
Student.update({'ID':10001, 'Department':'Science'})
print("\n Dictionary after adding multiple entries in one shot :", Student)
Output:
Dictionary after adding multiple entries in one shot : {' First_Name': 'Charles', 'Last_Name': 'Smith', 'ID': 10001, 'Department': 'Science'}
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith', 'ID': 10001, 'Department': 'Science'}
Student['Marks'] ={'Physics':100 ,'Chemistry':98}
print("\n Dictionary after nesting : \n ",Student)
Output:
Dictionary after nesting : {' First_Name': 'Charles', 'Last_Name': 'Smith', 'ID': 10001, 'Department': 'Science', 'Marks': {'Physics': 100, 'Chemistry': 98}}
We can also modify the dictionary by changing or replacing the existing values. This can be done by referring to its key. Below example, change the existing value, Smith to David, by referring to its key Last_Name.
We can also modify the dictionary by changing or replacing the existing values. This can be done by referring to its key. Below example, change the existing value, Smith to David, by referring to its key Last_Name.
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith'}
Student['Last_Name']='David'
print(Student)
Output:
{' First_Name': 'Charles', 'Last_Name': 'David'}
Another way to modify the dictionary is by removing the elements from it. There are various ways to remove or delete elements in the dictionary. They are listed below.
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith'}
print(Student.pop('Last_Name'))
print("Dictionary after removal is:",Student)
Output:
Smith Dictionary after removal is: {' First_Name': 'Charles'}
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith','Age':27}
print(Student.popitem())
print("Dictionary after removal is:",Student)
Output:
('Age', 27)
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith','Age':27}
print(Student.clear())
print("Dictionary after removal is:",Student)
Output:
None
Student = {' First_Name': 'Charles', 'Last_Name': 'Smith','Age':27}
del Student['Age']
print("Dictionary after removal is:",Student)
del Student
print("Dictionary after removal is:",Student)
Output:
Dictionary after removal is: {' First_Name': 'Charles', 'Last_Name': 'Smith'} print("Dictionary after removal is:",Student) NameError: name 'Student' is not defined
As in other data types, we can validate the presence of a key in a dictionary using the membership operators. The two membership operators are :
D ={
0:'Red',
2:'Green',
4:'Blue'
}
print(0 in D)
print(3 not in D)
Output:
True True
To accomplish some specific tasks python has got some built-in functions for dictionaries. They are well tabulated below.
Function | Description |
---|---|
all() | Returns True if all keys in the dictionary are True |
any() | Returns True if any of the keys in the dictionary is True |
len() | Returns the number of key-value pairs in the dictionary |
sorted() | Returns a list of keys which are sorted |
Like functions, the Python dictionary does have methods to perform special tasks and return specific values. They are listed below in the table below.
METHODS | DESCRIPTION |
---|---|
clear() | Clears all items in the dictionary |
copy() | Returns a shallow copy of the dictionary |
fromkeys(seq[,v]) | Returns a new dictionary with keys from the seq and associated values v. |
get(key[,d]) | Returns the associated values of the key. |
items() | Returns a list of key-value pair format |
keys() | Returns the list of keys in the dictionary |
pop(key[,d]) | Removes elements in a dictionary referring to its key |
popitem() | Removes and returns the last inserted entry |
setdefault(key[,d]) | To set the key to default if the key is not available |
update() | Returns the updated dictionary with new entries or replacing the existing one. |
values() | Returns the list of values in a dictionary |