Python Dictionary

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.

Mapping

Key Features of Python Dictionary

  •  Dictionary is mutable.
  •  Dictionaries are dynamic in nature.
  •  Dictionary can be nest like a list
  •  Keys are unique and immutable while values are mutable

How to create a dictionary in Python

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.

Syntax of Dictionary

<dict_name> = {
      <key>:<value>,
      <key>:<value>,
      .
      .
      <key>:<value>
}

Empty Dictionary: Python dictionary with zero items.

Example: How to define empty Dictionary

emp_dict ={}
print(type(emp_dict))

 

Output:


<class 'dict'>

Homogeneous Dictionary: A Dictionary with keys of the same immutable datatype.

Example: How to create a Homogeneous dictionary

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.

Example: Mixed dictionary

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().

Example: dict() function

fn_dict = dict({'Name':'John','Age':30})
print(fn_dict)

 

Output:


{'Name': 'John', 'Age': 30}

Properties of Key and Values in Dictionary

Two important factors in a python dictionary are Keys and Values. Their properties are listed below.

  1. The key must be unique means there should be no duplication. If a dictionary contains duplicate keys then the last assignment will be considered.

    Example:Illustrates keys doesn't hold duplicates

    
    fn_dict = dict({'Name':'John','Age':30 ,'Name':'Charles'})
    print(fn_dict)
     
    

    Output:

    
    {'Name': 'Charles', 'Age': 30}
    
  2. Keys are immutable means they are unchangeable over the lifetime after creation. Keys can be integer, string, tuples but never be a list.

    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'
    
  3. Values are free of restrictions and they can be any data type and can be of any length.

    Example: shows values can be of any type and any length

    
    D = {'odd':[1,3,5,7,9]}
    print(D)
     
    

    Output:

    {'odd': [1, 3, 5, 7, 9]}
    

What is a Nested Dictionary in Python?

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.

Nested Dictionary

Nested Dictionary

University= {
 'UN_Name':'Oxford',
 'Stud':{   'St1_Name':'Tom','St2_Name':'Becky' }
}
print(University) 

Output:

{'UN_Name': 'Oxford', 'Stud': {'St1_Name': 'Tom', 'St2_Name': 'Becky'}}

How to access dictionary values in Python?

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.

Accessing Values from Dictionary

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]

Accessing undefined Values

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.

KeyError while accessing an undefined key


D= { 'A':'Apple','B':'Banana'}
print(D.get('C'))
print(D['C'])
 

Output:


None
print(D['C'])
KeyError: 'C'

How to access values from a Nested Dictionary

Examples : Accessing values from a nested dictionary


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

How to modify Python Set

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.

  1. adding single entries to an empty dictionary

    Example: How to add an element to an empty set

    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'}
    
  2. update() function : to add multiple entries to dictionary in one shot

    Example: How to add multiples element in one shot

    
    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'}
    
  3. Nesting a dictionary by adding another dictionary

    Example: addition of dictionary to an existing dictionary

    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.

Example: Changing values in the dictionary


Student = {' First_Name': 'Charles', 'Last_Name': 'Smith'}
Student['Last_Name']='David'
print(Student)
 

Output:

{' First_Name': 'Charles', 'Last_Name': 'David'}

How to remove elements from a Dictionary in Python

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.

  1. pop() Method: is a built-in function in a dictionary. It is used to remove a distinct item from a dictionary by referring to its key and this method returns the removed value.

    Example: Removing an element from a dictionary using pop() method

    
    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'}
    
  2. popitem() Method: is a built-in function used to remove the last inserted key-value pair from the dictionary and will return the key-value pairs.

    Example: Removing element from a dictionary using popitem() method

    
    Student = {' First_Name': 'Charles', 'Last_Name': 'Smith','Age':27}
    print(Student.popitem())
    print("Dictionary after removal is:",Student)
     
    

    Output:

    
    ('Age', 27)
    
  3. clear() Method: is a built-in function used to remove or clear all the elements in a dictionary.

    Example: Removing element using clear() method

    
    Student = {' First_Name': 'Charles', 'Last_Name': 'Smith','Age':27}
    print(Student.clear())
    print("Dictionary after removal is:",Student)
     
    

    Output:

    None
    
  4. del keyword: can be used to remove either individual elements or the entire dictionary itself.

    Example: Removing element using del keyword

    
    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
    

How to perform Membership Validation in a Python Dictionary

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 :

  • in: returns true only when the key is present in the dictionary.
  • not in: returns false when the key is absent in the dictionary.

Example: Membership Validation


D ={
   0:'Red',
   2:'Green',
   4:'Blue'
   }
print(0 in D)
print(3 not in D)
 

Output:

True
True

Python Dictionary built-in functions

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

Python Dictionary Methods

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