Skip to content

Ilm o Irfan

Technologies

  • Home
  • Courses
    • Free Courses
  • Motivational Seminars
  • Blog
  • Books
  • Contact
  • Home
  • Courses
    • Free Courses
  • Motivational Seminars
  • Blog
  • Books
  • Contact
Explore Courses

Introduction to Python

  • October 1, 2022
  • Home
  • Free Book

Table of Contents

Chapter 32 - Dictionaries in Python

  • Authors
  • Ms. Samavi Salman
  • Dr. Rao Muhammad Adeel Nawab
  • Supporting Material
  • Download Supporting Material (Code): here

Quick Recap

  • Quick Recap – Lists in Python

In previous Chapter, I presented

  • List
    • A List is defined as an ordered collection of items, which may or may not have same data types
  • List Declaration
    • A List can be declared using two methods
      • Method 1: Use []
      • Method 2: Use list() Function
  • List Initialization
    • There are two methods to initialize a List
      • Method 1: Use []
      • Method 2: Use list() Function
  • Accessing Elements of a List
    • There are three methods to access element(s) of a List
      • Method 1 – Access Element(s) of a List using Indexing
      • Method 2 – Access Element(s) of a List using Negative Indexing
      • Method 3 – Access Element(s) of a List using Slicing
  • Operations on List
    • Operation 1 – Creation
    • Operation 2 – Insertion
    • Operation 3 – Traversal
    • Operation 4 – Searching
    • Operation 5 – Sorting
    • Operation 6 – Merging
    • Operation 7 – Updation
    • Operation 8 – Deletion
  • List Comprehension
    • List Comprehension provides a short and simple way to create a new List based on the values of an existing interrable (tuple, set, list etc.)
  • Nested List
    • A Nest List is a list of list(s)
  • Lambda Function
    • In Python, a Lambda Function is an anonymous function that is defined without a name

Dictionary

  • Dictionary
  • Definition 1
    • In Python, Dictionary is a data structure which stores data as a set of unique identifiers, each of which have an associated value
      • This Data Pairing is called key-value pair
    • key
      • The unique identifier is called the key for an item of data
    • value
      • A value is either the data being identified or the location of that data
  • Definition 2
    • A Dictionary is a collection of key-value pairs
    • Note
      • In each key-value pair, the kay is mapped to its associated value.
    • Data Type – key
      • A Dictionary key can be almost any Python Object, but
          • Mostly Strings and Numbers are used keys
    • Data Type – value
      • A Dictionary value can be any arbitrary Python Object
    • Purpose
      • The main purpose of a Dictionary is to easily and quickly
        • store, retrieve, and manipulate complex data
  • Ordered Dictionary vs Unordered Dictionary
  • Ordered Dictionary
    • In an Ordered Dictionary, items have a defined order, which cannot be changed
  • Unordered Dictionary
    • In an Unordered Dictionary, items do not a defined order

Declaring a Dictionary

  • Dictionary Declaration
  • A Dictionary can be declared using two methods
    • Method 1: Use {}
    • Method 2: Use dict() Function
  • In Sha Allah, in next Slides, I will present both methods in detail
  • Syntax - Method 1 (Use {})
  • The Syntax to declare a Dictionary using {} is as follows
				
					DICTIOANRY_NAME = {
          <key-01>: <value>,
          <key-02>: <value>,
          <key-03>: <value>,
                  .
                  .
                  .
          <key-N-2>: <value>,
          <key-N-1>: <value>,
          <key-N>: <value>
        }

				
			
  • Syntax – Method 2 (Use dict() Function)
  • The Syntax to declare a Dictionary using dict() Built in Function is as follows
				
					LIST_NAME = list([
               <value>,
               <value>,
               <value>,
                  .
                  .
                  .
               <value>,
               <value>,
               <value>
        ])
				
			

Declaring an Empty Dictionary

  • Declaring an Empty Dictionary
  • In Sha Allah, in the next Slides, I will show how to declare an Empty Dictionary using the following two Methods
    • Method 1: Use {}
    • Method 2: Use dict() Built in Function
  • Example 1 – Declaring an Empty Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Declaring an Empty Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to declare an empty dictionary using {} and dict() Function
'''

try:
    # Declare an Empty Dictionary - Method 1: Use {}
    print("---Declare an Empty Dictionary - Method 1: Use {}---")    
    
    # Declare an Empty Dictionary
    tomb_of_sahaba_1 = {}
        
    # Display Data Values of a Dictionary
    print("Data Values of tomb_of_sahaba_1:", tomb_of_sahaba_1)
    
    # Display Data-Type of a Dictionary using type() Function    
    print("Data-Type of tomb_of_sahaba_1:", type(tomb_of_sahaba_1))

    # Display Length of a Dictionary using len() Function
    print("Length of tomb_of_sahaba_1:", len(tomb_of_sahaba_1))
except:
    print("Error Occurred")

print("---------------------------------------------------------")

try:
    # Declare an Empty Dictionary - Method 2: Use dict() Function
    print("---Declare an Empty Dictionary - Use dict() Function---")    

    # Declare an Empty Dictionary
    tomb_of_sahaba_2 = dict()    

    # Display Data Values of a Dictionary
    print("Data Values of tomb_of_sahaba_2:", tomb_of_sahaba_2)
    
    # Display Data-Type of a Dictionary using type() Function
    print("Data-Type of tomb_of_sahaba_2:", type(tomb_of_sahaba_2))
    
    # Display Length of a Dictionary using len() Function
    print("Length of tomb_of_sahaba_2:", len(tomb_of_sahaba_2))
except:
    print("Error Occurred")

				
			
				
					---Declare an Empty Dictionary - Method 1: Use {}---
Data Values of tomb_of_sahaba_1: {}
Data-Type of tomb_of_sahaba_1: <class 'dict'>
Length of tomb_of_sahaba_1: 0
---------------------------------------------------------
---Declare an Empty Dictionary - Use dict() Function---
Data Values of tomb_of_sahaba_2: {}
Data-Type of tomb_of_sahaba_2: <class 'dict'>
Length of tomb_of_sahaba_2: 0

				
			
  • Example 2 – Declaring an Empty Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Declaring an Empty Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to declare an empty dictionary using {} and dict() Function
'''

try:
    # Declare an Empty Dictionary - Method 1: Use {}
    print("---Declare an Empty Dictionary - Method 1: Use {}---")    
    
    # Declare an Empty Dictionary
    products_1 = {}
        
    # Display Data Values of a Dictionary
    print("Data Values of products_1:", products_1)
    
    # Display Data-Type of a Dictionary using type() Function    
    print("Data-Type of products_1:", type(products_1))

    # Display Length of a Dictionary using len() Function
    print("Length of products_1:", len(products_1))
except:
    print("Error Occurred")

print("---------------------------------------------------------")

try:
    # Declare an Empty Dictionary - Method 2: Use dict() Function
    print("---Declare an Empty Dictionary - Use dict() Function---")    

    # Declare an Empty Dictionary
    products_2 = dict()    

    # Display Data Values of a Dictionary
    print("Data Values of products_2:", products_2)
    
    # Display Data-Type of a Dictionary using type() Function
    print("Data-Type of products_2:", type(products_2))
    
    # Display Length of a Dictionary using len() Function
    print("Length of products_2:", len(products_2))
except:
    print("Error Occurred")

				
			
				
					---Declare an Empty Dictionary - Method 1: Use {}---
Data Values of products_1: {}
Data-Type of products_1: <class 'dict'>
Length of products_1: 0
---------------------------------------------------------
---Declare an Empty Dictionary - Use dict() Function---
Data Values of products_2: {}
Data-Type of products_2: <class 'dict'>
Length of products_2: 0
				
			

Initializing a Dictionary

  • Initializing a Dictionary
  • In Sha Allah, in the next Slides, I will show how to initialize a Dictionary using the following two Methods
    • Method 1: Building a Complete Dictionary
    • Method 2: Building a Dictionary Incrementally
  • Suitable to Use - Method 1: Building a Complete Dictionary
  • Question
    • When it is suitable to build a complete Dictionary?
  • Answer
    • When we know all the key-value pairs in advance
  • Suitable to Use - Method 2: Building a Dictionary Incrementally
  • Question
    • When it is suitable to build a Dictionary incrementally?
  • Answer
    • When we do not know all the key-value pairs in advance and want to build a Dictionary on fly

Initializing a Dictionary - Method 1: Building a Complete Dictionary

  • Initializing a Dictionary - Method 1: Building a Complete Dictionary
  • In Sha Allah, I will build a complete dictionary using two Approaches
    • Approach 01: Use {}
    • Approach 02: Use dict() Built in Function
  • Example 1 – Initializing a Dictionary - Method 1: Building a Complete Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Initialize a Dictionary
programming_language 	= Python	
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to initialize a complete dictionary and display its content (data values) on the Output Screen
'''

try:
    # Dictionary Initialization - Method 1: Use {}
    print("---Dictionary Initialization - Use {}---")    

    tomb_of_sahaba_1 = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus'      , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Display Data Values of a Dictionary 
    print("Data Values of tomb_of_sahaba_1:", tomb_of_sahaba_1)

    # Display Length of a Dictionary using len() Function
    print("Length of tomb_of_sahaba_1:", len(tomb_of_sahaba_1))

    # Display Type of a Dictionary using type() Function
    print("Data-Type of tomb_of_sahaba_1:", type(tomb_of_sahaba_1))
except:
    print("Error Occurred")

print("---------------------------------------------------------")

try:
    # Dictionary Initialization - Method 2: Use dict() Function
    print("---Dictionary Initialization – Use dict() Function---")    

    tomb_of_sahaba_2 = dict({'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
  'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'})

    # Display Data Values of a Dictionary 
    print("Data Values of tomb_of_sahaba_2:", tomb_of_sahaba_2)

    # Display Length of a Dictionary using len() Function
    print("Length of tomb_of_sahaba_2:", len(tomb_of_sahaba_2))

    # Display Type of a Dictionary using type() Function
    print("Data-Type of tomb_of_sahaba_2:", type(tomb_of_sahaba_2))
except:
    print("Error Occurred")

				
			
				
					---Dictionary Initialization - Use {}---
Data Values of tomb_of_sahaba_1: {' Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
Length of tomb_of_sahaba_1: 6
Data-Type of tomb_of_sahaba_1: <class 'dict'>
---------------------------------------------------------
---Dictionary Initialization – Use dict() Function---
Data Values of tomb_of_sahaba_2: {'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
Length of tomb_of_sahaba_2: 6
Data-Type of tomb_of_sahaba_2: <class 'dict'>

				
			
  • Example 2 – Initializing a Dictionary - Method 1: Building a Complete Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Initialize a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to initialize a complete dictionary and display its content (data values) on the Output Screen
'''

try:
    # Dictionary Initialization - Method 1: Use {}
    print("---Dictionary Initialization - Use {}---")    

    products_1 = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}

    # Display Data Values of a Dictionary
    print("Data Values of products_1:", products_1)

    # Display Length of a Dictionary using len() Function
    print("Length of products_1:",len(products_1))

    # Display Type of a Dictionary using type() Function
    print("Data-Type of products_1:",type(products_1))
except:
    print("Error Occurred")

print("---------------------------------------------------------")

try:
    print("---Initialize a Dictionary - Method 2: dict()---")    

    # Dictionary Initialization - Method 2: Use dict() Function
    products_2 = dict({'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75})

    # Display Data Values of a Dictionary
    print("Data Values of products_2:", products_2)

    # Display Length of a Dictionary using len() Function
    print("Length of products_2:",len(products_2))

    # Display Type of a Dictionary using type() Function
    print("Data-Type of products_2:",type(products_2))
except:
    print("Error Occurred")

				
			
				
					---Dictionary Initialization - Use {}---
Data Values of products_1: {'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
Length of products_1: 6
Data-Type of products_1: <class 'dict'>
---------------------------------------------------------
---Initialize a Dictionary - Method 2: dict()---
Data Values of products_2: {'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
Length of products_2: 6
Data-Type of products_2: <class 'dict'>
				
			

Initializing a Dictionary - Method 2: Building a Dictionary Incrementally

  • Initializing a Dictionary - Method 2: Building a Dictionary Incrementally
  • In Sha Allah, to Build a Dictionary Incrementally (using {} Approach), we will follow a Two Step Process
  • Step 01: Declare an Empty Dictionary using {}
  • Step 02: Add Elements (key-value pairs) in the Dictionary (created in Step 1) as they become available
  • Example 1 – Initializing a Dictionary - Method 2: Building a Dictionary Incrementally
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Initialize a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to initialize a dictionary incrementally and display its content (data values) on the Output Screen
'''

try:
    # Dictionary Initialization using {}
    print("---Initialize a Dictionary - Use {}---")    

    tomb_of_sahaba = {}

    # Before Adding Elements in Dictionary
    print("Before Adding Elements in Dictionary \n", tomb_of_sahaba)

    # Building a Dictionary Incrementally
    tomb_of_sahaba['Shaddad bin Aus'] = 'Jerusalem'
    tomb_of_sahaba['Abu Ayub Ansari (R.A.)'] = 'Turkey',
    tomb_of_sahaba['Bilal (R.A.)'] = 'Damascus' ,
    tomb_of_sahaba['Prophet Zulkuf (R.A.)'] = 'Syria',
    tomb_of_sahaba['Hazrat Jabir bin Abdullah (R.A.)'] = 'Istanbul',
    tomb_of_sahaba['Saʿd ibn Abī Waqqās (R.A.)'] = 'China',
    tomb_of_sahaba['Ubadah As-Samit (R.A.)'] = 'Jerusalem'

    # After Adding Elements in Dictionary
    print("After Adding Elements in Dictionary \n", tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Initialize a Dictionary - Use {}---
Before Adding Elements in Dictionary 
 {}
After Adding Elements in Dictionary 
 {'Shaddad bin Aus': 'Jerusalem', 'Abu Ayub Ansari (R.A.)': ('Turkey',), 'Bilal (R.A.)': ('Damascus',), 'Prophet Zulkuf (R.A.)': ('Syria',), 'Hazrat Jabir bin Abdullah (R.A.)': ('Istanbul',), 'Saʿd ibn Abī Waqqās (R.A.)': ('China',), 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
				
			
  • Example 2 – Initializing a Dictionary - Method 2: Building a Dictionary Incrementally
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Initialize a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to initialize a dictionary incrementally and display its content (data values) on the Output Screen
'''

try:
    # Dictionary Initialization using {}
    print("---Initialize a Dictionary - Use {}---")

    products = {}
    
    # Before Adding Elements in Dictionary
    print("Before Adding Elements in Dictionary \n", products)

    # Building a Dictionary Incrementally
    products['Milk'] = 150.15,
    products['Honey'] = 900.25,
    products['Dates'] = 700.55,
    products['Olive Oil'] = 3000.7,
    products['Almond'] = 1000.2,
    products['Pumpkin'] = 60.75,
    products['Grapes'] = 150.12
    
    # After Adding Elements in Dictionary
    print("After Adding Elements in Dictionary \n", products)
except:
    print("Error Occurred")

				
			
				
					---Initialize a Dictionary - Use {}---
Before Adding Elements in Dictionary 
 {}
After Adding Elements in Dictionary 
 {'Milk': (150.15,), 'Honey': (900.25,), 'Dates': (700.55,), 'Olive Oil': (3000.7,), 'Almond': (1000.2,), 'Pumpkin': (60.75,), 'Grapes': 150.12}
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Declare and Initialize a Dictionary called phone_dir using the {} and dict() Function?
  • Note
    • The key-value pair of a Dictionary are as follows
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Human Engineering’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Spiritual Training Courses’: [‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

Your Turn Tasks

Your Turn Task 1

  • Task
    • Declare and Initialize a Dictionary (similar to the one given in TODO Task 1) using the {} and dict() Function?

Access value of an Individual Dictionary Item

  • Accessing Elements of a Dictionary
  • In Sha Allah, in next Slides, I will present two methods to access element(s) of a Dictionary
    • Method 1 – Access Element(s) of a Dictionary using key Name inside []
    • Method 2 – Access Element(s) of a Dictionary using get() built-in Functions
  • Access Element(s) of a Dictionary using key Name inside []
  • To access dictionary elements, square brackets along with the key is used to obtain its value
  • Syntax - Access Element(s) of a Dictionary using key Name inside []
				
					dict['key']
				
			
  • get() Function
  • Function Name
    • get()
  • Definition
    • The get() method returns the value of the item with the specified key.
  • Purpose
    • The main purpose of get() built-in Function is to
      • get the value against a particular key

Syntax

				
					dict.get(key, default = None)
				
			

Access Element(s) of a Dictionary using key Name inside []

  • Example 1 - Access Element(s) of a Dictionary using key Name inside []
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary 
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using key name
'''

try:  
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}

    # Access Element(s) of a Dictionary using Keys
    print("---Access Element(s) of a Dictionary using Keys---")

    print("products['Milk']:",products['Milk'])
    print("products['Honey']:",products['Honey'])
    print("products['Dates']:",products['Dates'])
    print("products['Olive Oil']:",products['Olive Oil'])
    print("products['Almond']:",products['Almond'])
    print("products['Pumpkin']:",products['Pumpkin'])
except:
    print("Error Occurred")

				
			
				
					---Access Element(s) of a Dictionary using Keys---
products['Milk']: 150.15
products['Honey']: 900.25
products['Dates']: 700.55
products['Olive Oil']: 3000.7
products['Almond']: 1000.2
products['Pumpkin']: 60.75

				
			
  • Example 2 - Access Element(s) of a Dictionary using key Name inside []
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using key name
'''

try:  
    tomb_of_sahaba = {'Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,
    'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Access Element(s) of a Dictionary using Keys
    print("---Access Element(s) of a Dictionary using Keys---")

    print(tomb_of_sahaba[' Ayub Ansari (R.A.)'])
    print(tomb_of_sahaba['Bilal (R.A.)'])
    print(tomb_of_sahaba['Prophet Zulkuf (R.A.)'])
    print(tomb_of_sahaba['Hazrat Jabir bin Abdullah (R.A.)'])
    print(tomb_of_sahaba['Saʿd ibn Abī Waqqās (R.A.)'])
    print(tomb_of_sahaba['Ubadah As-Samit (R.A.)'])
except:
    print("Error Occurred")

				
			
				
					---Access Element(s) of a Dictionary using Keys---
Turkey
Damascus
Syria
Istanbul
China
Jerusalem
				
			

Access Element(s) of a Dictionary using get() built-in Functions

  • Example 1 - Access Element(s) of a Dictionary using get() built-in Functions
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary using get() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using get() Function
'''

try:  
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Access Element(s) of a Dictionary using get() Function
    print("---Access Element(s) of a Dictionary using get() Function---")
    
    print(tomb_of_sahaba.get('Abu Ayub Ansari (R.A.)'))
    print(tomb_of_sahaba.get('Bilal (R.A.)'))
    print(tomb_of_sahaba.get('Prophet Zulkuf (R.A.)'))
    print(tomb_of_sahaba.get('Hazrat Jabir bin Abdullah (R.A.)'))
    print(tomb_of_sahaba.get('Saʿd ibn Abī Waqqās (R.A.)'))
    print(tomb_of_sahaba.get('Ubadah As-Samit (R.A.)'))
except:
    print("Error Occurred")

				
			
				
					---Access Element(s) of a Dictionary using get() Function---
Turkey
Damascus
Syria
Istanbul
China
Jerusalem
				
			
  • Example 2 - Access Element(s) of a Dictionary using get() built-in Functions
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary using get() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using get() Function
'''

try:  
    # Initialize Dictionary
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}

    # Access Element(s) of a Dictionary using get() Function
    print("---Access Element(s) of a Dictionary using get() Function---")
    
    print(products.get('Milk'))
    print(products.get('Honey'))
    print(products.get('Dates'))
    print(products.get('Olive Oil'))
    print(products.get('Almond'))
    print(products.get('Pumpkin'))
except:
    print("Error Occurred")
				
			
				
					---Access Element(s) of a Dictionary using get() Function---
150.15
900.25
700.55
3000.7
1000.2
60.75
				
			

Access List of keys in a Dictionary

  • Accessing Elements of a Dictionary
  • In Sha Allah, in next Slides, I will present a method to access element(s) of a Dictionary
    • Access List of keys in a Dictionary using key() built-in Function
  • key() Function
  • Function Name
    • key()
  • Definition
    • The keys() method returns a view object. The view object contains the keys of the dictionary, as a list
  • Purpose
    • The main purpose of key() built-in Function is to
      • returns all keys from a Dictionary
  • Syntax
				
					dict.keys()
				
			
  • values() Function
  • Function Name
    • values()
  • Definition
    • The values() method returns a view object. The view object contains the values of the dictionary, as a list
  • Purpose
    • The main purpose of values() built-in Function is to
      • returns all values from a Dictionary
  • Syntax
				
					dict.values()
				
			

Access List of keys in a Dictionary using key() built-in Function

  • Example 1 - Access List of keys in a Dictionary using key() built-in Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access List of Keys in a Dictionary using key() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access list of keys in a dictionary using key() function 
'''

try:  
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Access Element(s) of a Dictionary using key() Function
    print("---Access Element(s) of a Dictionary using key() Function---")   
    print(tomb_of_sahaba.keys())
except:
    print("Error Occurred")
				
			
				
					---Access Element(s) of a Dictionary using key() Function---
dict_keys(['Abu Ayub Ansari (R.A.)', 'Bilal (R.A.)', 'Prophet Zulkuf (R.A.)', 'Hazrat Jabir bin Abdullah (R.A.)', 'Saʿd ibn Abī Waqqās (R.A.)', 'Ubadah As-Samit (R.A.)'])
				
			
  • Example 2 - Access List of keys in a Dictionary using key() built-in Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access List of Keys in a Dictionary using key() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access list of keys in a dictionary using key() function 
'''

try:  
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}

    # Access Element(s) of a Dictionary using key() Function
    print("---Access Element(s) of a Dictionary using key() Function---")  
    print(products.keys())
except:
    print("Error Occurred")
				
			
				
					---Access Element(s) of a Dictionary using key() Function---
dict_keys(['Milk', 'Honey', 'Dates', 'Olive Oil', 'Almond', 'Pumpkin'])
				
			

Access List of values in a Dictionary

  • Access List of values in a Dictionary
  • In Sha Allah, in next Slides, I will present a method to access element(s) of a Dictionary
    • Access List of values in a Dictionary using values() built-in Function

Access List of values in a Dictionary using values() built-in Function

  • Example 1 - Access List of values in a Dictionary using values() built-in Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary using values() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using values() function 
'''

try:  
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Access Element(s) of a Dictionary using values() Function
    print("---Access Element(s) of a Dictionary using values() Function---")
    print(tomb_of_sahaba.values())
except:
    print("Error Occurred")
				
			
				
					---Access Element(s) of a Dictionary using values() Function---
dict_values(['Turkey', 'Damascus', 'Syria', 'Istanbul', 'China', 'Jerusalem'])
				
			
  • Example 2 - Access List of values in a Dictionary using values() built-in Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Element(s) of a Dictionary using values() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access element(s) of a dictionary using values() function 
'''

try:  
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}

    # Access Element(s) of a Dictionary using values() Function
    print("---Access Element(s) of a Dictionary using values() Function---")
    print(products.values())
except:
    print("Error Occurred")
				
			
				
					---Access Element(s) of a Dictionary using values() Function---
dict_values([150.15, 900.25, 700.55, 3000.7, 1000.2, 60.75])

				
			

Operations on Lists

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

        ‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

        ‘Human Engineering’:

        [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

        ‘Spiritual Training Courses’:

        [‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Access Elements of the phone_dir and courses Dictionaries suing
      • Access value of an Individual Dictionary Item
        • Method 1 – Access Element(s) of a Dictionary using key Name inside []
        • Method 2 – Access Element(s) of a Dictionary using get() built-in Functions
      • Access List of keys in a Dictionary using key() built-in Function
        • Access List of keys in a Dictionary using key() built-in Function
      • Access List of values in a Dictionary
      • Access List of values in a Dictionary using values() built-in Function
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Access Elements of the phone_dir and courses Dictionaries suing
      • Access value of an Individual Dictionary Item
        • Method 1 – Access Element(s) of a Dictionary using key Name inside []
        • Method 2 – Access Element(s) of a Dictionary using get() built-in Functions
      • Access List of keys in a Dictionary using key() built-in Function
      • Access List of keys in a Dictionary using key() built-in Function
      • Access List of values in a Dictionary
      • Access List of values in a Dictionary using values() built-in Function

Operations on Dictionaries

Operation 1 – Creation

  • Methods to Create a Dictionary
  • I have already presented methods to create a Dictionary in the previous Section e.,
    • Dictionary Initialization

Operation 2 – Insertion

Methods to Add Element(s) in a Dictionary

  • Methods to Add Element(s) in a List
  • Dictionaries have no order, and thus have no beginning or end. The order is arbitrary. So, in order to add Element(s) in a Dictionary, convert Dictionary to a List using items()
  • In Sha Allah, in next Slides, I will present three methods to add element(s) in a Dictionary
    • Method 1 – Add New Element(s) at the Start of a Dictionary
    • Method 2 – Add New Element(s) at the End of a Dictionary
    • Method 3 – Add New Element(s) at a Desired Location of a Dictionary
  • Item() Function
  • Function Name
    • item()
  • Definition
    • The items() method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list
  • Purpose
    • The main purpose of item() built-in Function is to
      • Convert dictionary to a list
				
					dict.items()
				
			

Add a New Element at the Start of a Dictionary

  • Add a New Element at the Start of a Dictionary
  • In Sha Allah, in the next Slides, we will show how to Add New Element(s) at Start of a Dictionary using
    • insert() Built-in Function
  • Example 1 – Add a New Element at the Start of a Dictionary – Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at the Start of a Dictionary 
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add a new element at the start of a Dictionary on the output screen
'''

try:
    print("---Add a Single Element at Start of a Dictionary---")    
	
    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus'    , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
  'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Adding Element at Start of a Dictionary---")
    print(tomb_of_sahaba)
    
    # Data Type of i.e., tomb_of_sahaba before converting to List
    print("---Data Type of i.e., tomb_of_sahaba before converting to List---")
    print(type(tomb_of_sahaba))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_tomb_of_sahaba = list(tomb_of_sahaba.items())

    # Data Type of i.e., tomb_of_sahaba after converting to List
    print("---Data Type of i.e., tomb_of_sahaba after converting to List---")
    print(type(list_tomb_of_sahaba))

    # Add Data Value at Start of a Dictionary using insert() Function 
    list_tomb_of_sahaba.insert(0, ('Hazrat Abu Derda','Turkey'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element at Start of a Dictionary---")
    print(list_tomb_of_sahaba)

    print("-------------------------------------------------------------")

    print("---Again Add a Single Element at Start of a Dictionary---")    

    print("---Original Dictionary before Adding Element at Start of a Dictionary---")
    print(tomb_of_sahaba)
    
    # Add Data Value at Start of a Dictionary using insert() Function 
    list_tomb_of_sahaba.insert(0, ('Hazrat Abu Seyb el-Hudri','Turkey'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element at Start of a Dictionary---")
    print(list_tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Add a Single Element at Start of a Dictionary---
---Original Dictionary before Adding Element at Start of a Dictionary---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---Data Type of i.e., tomb_of_sahaba before converting to List---
<class 'dict'>
---Data Type of i.e., tomb_of_sahaba after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element at Start of a Dictionary---
[('Hazrat Abu Derda', 'Turkey'), ('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]
-------------------------------------------------------------
---Again Add a Single Element at Start of a Dictionary---
---Original Dictionary before Adding Element at Start of a Dictionary---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---Updated Dictionary after Adding Element at Start of a Dictionary---
[('Hazrat Abu Seyb el-Hudri', 'Turkey'), ('Hazrat Abu Derda', 'Turkey'), ('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]

				
			
  • Example 2 – Add a New Element at the Start of a Dictionary – Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at the Start of a Dictionary 
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add a new element at the start of a Dictionary on the output screen
'''

try:
    print("---Add a Single Element at Start of a Dictionary---")    
	
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Adding Element at Start of a Dictionary---")
    print(products)
    
    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(products))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_products = list(products.items())

    # Data Type of i.e., products after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_products))

    # Add Data Value at Start of a Dictionary using insert() Function 
    list_products.insert(0, ('grapes','500.35'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element at Start of a Dictionary---")
    print(list_products)

    print("-------------------------------------------------------------")

    print("---Again Add a Single Element at Start of a Dictionary---")    

    print("---Original Dictionary before Adding Element at Start of a Dictionary---")
    print(products)
    
    # Add Data Value at Start of a Dictionary using insert() Function 
    list_products.insert(0, ('banana','100.95'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element at Start of a Dictionary---")
    print(list_products)
except:
    print("Error Occurred")

				
			
				
					---Add a Single Element at Start of a Dictionary---
---Original Dictionary before Adding Element at Start of a Dictionary---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element at Start of a Dictionary---
[('grapes', '500.35'), ('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Olive Oil', 3000.7), ('Almond', 1000.2), ('Pumpkin', 60.75)]
-------------------------------------------------------------
---Again Add a Single Element at Start of a Dictionary---
---Original Dictionary before Adding Element at Start of a Dictionary---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Updated Dictionary after Adding Element at Start of a Dictionary---
[('banana', '100.95'), ('grapes', '500.35'), ('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Olive Oil', 3000.7), ('Almond', 1000.2), ('Pumpkin', 60.75)]
				
			

Add Multiple Elements at the Start of a Dictionary

  • Example 1 – Add Multiple Elements at the Start of a Dictionary – Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add Multiple Elements at the Start of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
the main purpose of the program is to add multiple elements at the start of a dictionary 
'''

try:
    print("---Add a Multiple Elements at Start of a Dictionary---")    
	
    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus'    , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
  'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Adding Element(s) at Start of a Dictionary---")
    print(tomb_of_sahaba)
    
    # Data Type of i.e., tomb_of_sahaba before converting to List
    print("---Data Type of i.e., tomb_of_sahaba before converting to List---")
    print(type(tomb_of_sahaba))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_tomb_of_sahaba = list(tomb_of_sahaba.items())

    # Data Type of i.e., tomb_of_sahaba after converting to List
    print("---Data Type of i.e., tomb_of_sahaba after converting to List---")
    print(type(list_tomb_of_sahaba))

    # Add Data Value at Start of a Dictionary using insert() Function 
    list_tomb_of_sahaba.insert(0, ('Hazrat Abu Derda','Turkey'))
    list_tomb_of_sahaba.insert(0, ('Hazrat Abu Seyb el-Hudri','Turkey'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element(s) at Start of a Dictionary---")
    print(list_tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Add a Multiple Elements at Start of a Dictionary---
---Original Dictionary before Adding Element(s) at Start of a Dictionary---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---Data Type of i.e., tomb_of_sahaba before converting to List---
<class 'dict'>
---Data Type of i.e., tomb_of_sahaba after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element(s) at Start of a Dictionary---
[('Hazrat Abu Seyb el-Hudri', 'Turkey'), ('Hazrat Abu Derda', 'Turkey'), ('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]
				
			
  • Example 2 – Add Multiple Elements at the Start of a Dictionary – Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add Multiple Elements at the Start of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
the main purpose of the program is to add multiple elements at the start of a dictionary 
'''

try:
    print("---Add a Multiple Elements at Start of a Dictionary---")    
    
	
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Adding Element(s) at Start of a Dictionary---")
    print(products)
    
    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(products))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_products = list(products.items())

    # Data Type of i.e., products after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_products))

    # Add Data Value at Start of a Dictionary using insert() Function 
    list_products.insert(0, ('grapes','500.35'))
    list_products.insert(0, ('banana','100.95'))

    # Display Updated Dictionary after Adding Element at Start of a Dictionary 
    print("---Updated Dictionary after Adding Element(s) at Start of a Dictionary---")
    print(list_products)
except:
    print("Error Occurred")

				
			
				
					---Add a Multiple Elements at Start of a Dictionary---
---Original Dictionary before Adding Element(s) at Start of a Dictionary---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element(s) at Start of a Dictionary---
[('banana', '100.95'), ('grapes', '500.35'), ('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Olive Oil', 3000.7), ('Almond', 1000.2), ('Pumpkin', 60.75)]

				
			

Add a New Element at the End of a Dictionary

  • Add a New Element at the End of a Dictionary
  • In Sha Allah, in the next Slides, we will show how to Add New Element(s) at End of a Dictionary using
    • append() Built-in Function
  • Example 1 – Add a New Element at the End of a Dictionary – Using append() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at the End of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add a new element at the end of a dictionary
'''

try:
    print("---Add a Single Element at End of a Dictionary---")    

    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Adding Element at End of a Dictionary---")
    print(tomb_of_sahaba)

    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., tomb_of_sahaba before converting to List---")
    print(type(tomb_of_sahaba))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_tomb_of_sahaba = list(tomb_of_sahaba.items())

    # Data Type of i.e., tomb_of_sahaba after converting to List
    print("---Data Type of i.e., tomb_of_sahaba after converting to List---")
    print(type(tomb_of_sahaba))

    # Add Data Value at Start of a Dictionary using append() Function 
    list_tomb_of_sahaba.append(('Hazrat Abu Derda','Turkey'))

    # Display Updated Dictionary after Adding Element at End of a Dictionary 
    print("---Updated Dictionary after Adding Element at End of a Dictionary---")
    print(list_tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Add a Single Element at End of a Dictionary---
---Original Dictionary before Adding Element at End of a Dictionary---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---Data Type of i.e., tomb_of_sahaba before converting to List---
<class 'dict'>
---Data Type of i.e., tomb_of_sahaba after converting to List---
<class 'dict'>
---Updated Dictionary after Adding Element at End of a Dictionary---
[('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem'), ('Hazrat Abu Derda', 'Turkey')]
				
			
  • Example 2 – Add a New Element at the End of a Dictionary – Using append() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at the End of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add a new element at the end of a dictionary
'''

try:
    print("---Add a Single Element at End of a Dictionary---")    

    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Adding Element at End of a Dictionary---")
    print(products)

    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(products))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_products = list(products.items())

    # Data Type of i.e., products after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_products))

    # Add Data Value at Start of a Dictionary using append() Function 
    list_products.append(('grapes','500.35'))

    # Display Updated Dictionary after Adding Element at End of a Dictionary 
    print("---Updated Dictionary after Adding Element at End of a Dictionary---")
    print(list_products)
except:
    print("Error Occurred")

				
			
				
					---Add a Single Element at End of a Dictionary---
---Original Dictionary before Adding Element at End of a Dictionary---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element at End of a Dictionary---
[('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Olive Oil', 3000.7), ('Almond', 1000.2), ('Pumpkin', 60.75), ('grapes', '500.35')]

				
			

Add Multiple Elements at the End of a Dictionary

  • Example 1 – Add Multiple Elements at the End of a Dictionary – Using append() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add Multiple Elements at the End of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add multiple elements at the end of a Dictionary
'''	

try:
    print("---Add Multiple Elements at End of a Dictionary---")    

    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China'}
    
    print("---Original Dictionary before Adding Element(s) at End of a Dictionary---")
    print(tomb_of_sahaba)

    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., tomb_of_sahaba before converting to List---")
    print(type(tomb_of_sahaba))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_tomb_of_sahaba = list(tomb_of_sahaba.items())

    # Data Type of i.e., tomb_of_sahaba after converting to List
    print("---Data Type of i.e., tomb_of_sahaba after converting to List---")
    print(type(tomb_of_sahaba))

    # Add Data Value at Start of a Dictionary using append() Function 
    list_tomb_of_sahaba.append(('Hazrat Abu Derda','Turkey'))
    list_tomb_of_sahaba.append(('Ubadah As-Samit (R.A.)', 'Jerusalem'))

    # Display Updated Dictionary after Adding Element(s) at End of a Dictionary 
    print("---Updated Dictionary after Adding Element(s) at End of a Dictionary---")
    print(list_tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Add Multiple Elements at End of a Dictionary---
---Original Dictionary before Adding Element(s) at End of a Dictionary---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China'}
---Data Type of i.e., tomb_of_sahaba before converting to List---
<class 'dict'>
---Data Type of i.e., tomb_of_sahaba after converting to List---
<class 'dict'>
---Updated Dictionary after Adding Element(s) at End of a Dictionary---
[('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Hazrat Abu Derda', 'Turkey'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]

				
			
  • Example 2 – Add Multiple Elements at the End of a Dictionary – Using append() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add Multiple Elements at the End of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add multiple elements at the end of a Dictionary
'''	

try:
    print("---Add Multiple Element(s) at End of a Dictionary---")    

    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Adding Element(s) at End of a Dictionary---")
    print(products)

    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(products))

    # Converting a Dictionary into a List and store list in "list_tomb_of_sahaba"
    list_products = list(products.items())

    # Data Type of i.e., products after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_products))

    # Add Data Value at Start of a Dictionary using append() Function 
    list_products.append(('grapes','500.35'))

    # Display Updated Dictionary after Adding Element(s) at End of a Dictionary 
    print("---Updated Dictionary after Adding Element(s) at End of a Dictionary---")
    print(list_products)
except:
    print("Error Occurred")

				
			
				
					---Add Multiple Element(s) at End of a Dictionary---
---Original Dictionary before Adding Element(s) at End of a Dictionary---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element(s) at End of a Dictionary---
[('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Olive Oil', 3000.7), ('Almond', 1000.2), ('Pumpkin', 60.75), ('grapes', '500.35')]

				
			

Add New Element(s) at a Desired Location of a Dictionary

  • Add New Element(s) at a Desired Location of a Dictionary
  • In Sha Allah, in the next Slides, we will show how to add new element to the Desired Location of a Dictionary using
    • insert() Built-in Function
  • Example 1 – Add a New Element at a Desired Location of a Dictionary - Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at a Desired Location of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
the main purpose of the program is to add a new element at a desired location of a Dictionary on the output screen
'''

try:
    print("---Add Element at Desired Location of a Dictionary---")    
    
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
    'Saʿd ibn Abī Waqqās (R.A.)' : 'China'}

    print("---Original Dictionary before Adding Element(s)---")
    print(tomb_of_sahaba)

    # Data Type of i.e., tomb_of_sahaba before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(tomb_of_sahaba))

    # Converting a Dictionary into a List and store list in "tomb_of_sahaba"
    list_tomb_of_sahaba = list(tomb_of_sahaba.items())

    # Data Type of i.e., tomb_of_sahaba after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_tomb_of_sahaba))

    # Add Data Value at desired location of a Dictionary using insert() Function 
    list_tomb_of_sahaba.insert(3,('Hazrat Abu Derda','Turkey'))
    list_tomb_of_sahaba.insert(6,('Ubadah As-Samit (R.A.)', 'Jerusalem'))

    # Display Updated Dictionary after Adding Element(s)
    print("---Updated Dictionary after Adding Element(s)---")
    print(list_tomb_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Add Element at Desired Location of a Dictionary---
---Original Dictionary before Adding Element(s)---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China'}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element(s)---
[('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Abu Derda', 'Turkey'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]

				
			
  • Example 2 – Add a New Element at a Desired Location of a Dictionary – Using insert() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add a New Element at a Desired Location of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 29-Jun-2022
end_data 			= 3-Jul-2022
'''

'''
Purpose of Program 
the main purpose of the program is to add a new element at a desired location of a Dictionary on the output screen
'''

try:
    print("---Add Element at Desired Location of a Dictionary---")    
    
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Adding Element(s)---")
    print(products)

    # Data Type of i.e., products before converting to List
    print("---Data Type of i.e., products before converting to List---")
    print(type(products))

    # Converting a Dictionary into a List and store list in "products"
    list_products = list(products.items())

    # Data Type of i.e., products after converting to List
    print("---Data Type of i.e., products after converting to List---")
    print(type(list_products))

    # Add Data Value at desired location of a Dictionary using insert() Function 
    list_products.insert(3,('grapes','500.35'))
    list_products.insert(5, ('banana','100.95'))

    # Display Updated Dictionary after Adding Element(s)
    print("---Updated Dictionary after Adding Element(s)---")
    print(list_products)
except:
    print("Error Occurred")

				
			
				
					---Add Element at Desired Location of a Dictionary---
---Original Dictionary before Adding Element(s)---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---Data Type of i.e., products before converting to List---
<class 'dict'>
---Data Type of i.e., products after converting to List---
<class 'list'>
---Updated Dictionary after Adding Element(s)---
[('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('grapes', '500.35'), ('Olive Oil', 3000.7), ('banana', '100.95'), ('Almond', 1000.2), ('Pumpkin', 60.75)]

				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Human Engineering’:

[‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Spiritual Training Courses’:

[‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Insert Elements to prophets and ages Dictionaries using following methods (as shown in this Chapter)
      • Method 1 – Add a New Element at the Start of a Dictionary
      • Method 2 – Add a New Element at the End of a Dictionary
      • Method 3 – Add a New Element at a Desired Location of a Dictionary
Your Turn Tasks

Your Turn Task 1

  • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Insert Elements to selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1 – Add a New Element at the Start of a Dictionary
      • Method 2 – Add a New Element at the End of a Dictionary
      • Method 3 – Add a New Element at a Desired Location of a Dictionary

Operation 3 – Traverse

  • Methods to Traverse a Dictionary
  • In Sha Allah, in next Slides, I will present three methods to traverse a Dictionary
    • Method 1: Traverse through all keys
    • Method 2: Traverse through all values
    • Method 3: Traverse through all key, value pairs

Traverse through all keys

  • Example 1 - Traverse through all keys
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all keys
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all keys and display the result on the output screen
'''

try:
    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',
  'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}    
  
    # Traverse through all keys
    print("---Traverse through all Keys---")
    for tombs in tomb_of_sahaba:
        print(tombs)
except:	
    print('Error Occurred')
				
			
				
					[' Hazrat Abu Bakr Siddique R.A.', 'Hazrat Umar.e.Farooq R.A.', 'Hazrat Usman.e.Ghani R.A.', 'Hazrat Ali ul Murtaza R.A.']---Traverse through all Keys---
Abu Ayub Ansari (R.A.)
Bilal (R.A.)
Prophet Zulkuf (R.A.)
Hazrat Jabir bin Abdullah (R.A.)
Saʿd ibn Abī Waqqās (R.A.)
Ubadah As-Samit (R.A.)
				
			
  • Example 2 - Traverse through all keys
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all keys
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all keys and display the result on the output screen
'''

try:
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    # Traverse through all keys
    print("---Traverse through all Keys---")
    for product in products:
        print(product)
except:	
    print('Error Occurred')
				
			
				
					---Traverse through all Keys---
Milk
Honey
Dates
Olive Oil
Almond
Pumpkin
				
			

Traverse through all Values

  • Example 1 - Traverse through all Values
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all values
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all values and display the result on the output screen
'''


try:
    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
  
    # Traverse through all keys
    print("---Traverse through all Values---")
    for tombs in tomb_of_sahaba.values():
        print(tombs)
except:	
    print('Error Occurred')
				
			
				
					---Traverse through all Values---
Turkey
Damascus
Syria
Istanbul
China
Jerusalem
				
			
  • Example 2 - Traverse through all Values
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all values
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all values and display the result on the output screen
'''

try:
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    # Traverse through all Values
    print("---Traverse through all Values---")
    for product in products.values():
        print(product)
except:	
    print('Error Occurred')
				
			
				
					---Traverse through all Values---
150.15
900.25
700.55
3000.7
1000.2
60.75
				
			

Traverse through all key, value pairs

  • Example 1 - Traverse through all key, value pairs
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all key, value pairs
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all key, value pairs and display the result on the output screen
'''

try:
    # Dictionary Initialization
    tomb_of_sahaba  = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
  
    # Traverse through all key, value pairs
    print("---Traverse through all key, value pairs---")
    for tombs in tomb_of_sahaba.items():
        print(tombs)
except:	
    print('Error Occurred')
				
			
				
					---Traverse through all key, value pairs---
('Abu Ayub Ansari (R.A.)', 'Turkey')
('Bilal (R.A.)', 'Damascus')
('Prophet Zulkuf (R.A.)', 'Syria')
('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul')
('Saʿd ibn Abī Waqqās (R.A.)', 'China')
('Ubadah As-Samit (R.A.)', 'Jerusalem')
				
			
  • Example 2 - Traverse through all key, value pairs
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traverse through all key, value pairs
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to traverse through all key, value pairs and display the result on the output screen
'''

try:
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    # Traverse through all key, value pairs
    print("---Traverse through all key, value pairs---")
    for product in products.items():
        print(product)
except:	
    print('Error Occurred')

				
			
				
					---Traverse through all key, value pairs---
('Milk', 150.15)
('Honey', 900.25)
('Dates', 700.55)
('Olive Oil', 3000.7)
('Almond', 1000.2)
('Pumpkin', 60.75)
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}

                            courses = { ‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

                                      ‘Human Engineering’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

                                      ‘Spiritual Training Courses’: [‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’] }

  • Questions
    • Traverse selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Traversing an Entire Dictionary
      • Method 2: Traversing a Dictionary (Element by Element)
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Traverse selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Traversing an Entire Dictionary
      • Method 2: Traversing a Dictionary (Element by Element)

Operation 4 – Searching

  • Methods to Search Character from a Dictionary
  • In Sha Allah, in next Slides, I will present two methods to search a Dictionary
    • Method 1: Search Element(s) from a Dictionary using key
    • Method 2: Search Element(s) from a Dictionary using value
  • Example 1 – Search Element(s) from a Dictionary using key
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Search Element(s) using Key
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to search element(s) using key
'''

try:
    tomb_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 
    'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',  'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    # Search Value using Key from a Dictionary    
    print ("Value against 'Saʿd ibn Abī Waqqās (R.A.)' : "+ tomb_of_sahaba.get('Saʿd ibn Abī Waqqās (R.A.)'))
    print ("Value against Bilal (R.A.): " + tomb_of_sahaba.get('Bilal (R.A.)'))    except:
    print('Error Occurred')
				
			
				
					Value against 'Saʿd ibn Abī Waqqās (R.A.)' : China
Value against Bilal (R.A.): Damascus
				
			
  • Example 2 – Search Element(s) from a Dictionary using key
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Search Element(s) using Key
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to search element(s) using key
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}    
    
    # Search Value using Key from a Dictionary    
    print ("Value against Pumpkin: ", products.get('Pumpkin'))
    print ("Value against Olive Oil: " , products.get('Olive Oil'))
except:
    print('Error Occurred')
				
			
				
					Value against Pumpkin:  60.75
Value against Olive Oil:  3000.7
				
			

Search by Value

  • Example 1 – Search Element(s) from a Dictionary using Value
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Search Element(s) using Value
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to search element(s) using value
'''

try:
    # Approach I - Using Keys(), Values() and index()
    tomb_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul',  "Sa'd ibn Abi Waqqās (R.A.)" : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}    

    print("---Approach I - Using Keys(), Values() and index()---")

    # Store all Keys from the Dictionary in the Variable i.e., key_list
    key_list = list(tomb_of_sahaba.keys())
    print("Keys in the Dictionary:", key_list)

    # Store all Values from the Dictionary in the Variable i.e., val_list
    val_list = list(tomb_of_sahaba.values())
    print("Values in the Dictionary:", val_list)

    print("---------------------------------------------------------")

    # Store Index of Value 'China' in a Variable i.e., position
    position_China = val_list.index('China')
    # Display the Key with Value 'China'
    print("Key against Value 'China':",key_list[position_China])
 
    # Store Index of Value 'Syria' in a Variable i.e., position
    position_Syria = val_list.index('Syria')
    # Display the Key with Value 'Syria'
    print("Key against Value 'Syria':",key_list[position_Syria])
    
    print("---------------------------------------------------------")

    # Approach II - Using OneLiner

    print("---Approach II - Using OneLiner---")
    print("Key against Value 'China':",list(tomb_of_sahaba.keys())[list(tomb_of_sahaba.values()).index('China')])
    print("Key against Value 'Syria':",list(tomb_of_sahaba.keys())[list(tomb_of_sahaba.values()).index('Syria')])  
except Exception as ex:
    print(ex)

				
			
				
					---Approach I - Using Keys(), Values() and index()---
Keys in the Dictionary: ['Abu Ayub Ansari (R.A.)', 'Bilal (R.A.)', 'Prophet Zulkuf (R.A.)', 'Hazrat Jabir bin Abdullah (R.A.)', "Sa'd ibn Abi Waqqās (R.A.)", 'Ubadah As-Samit (R.A.)']
Values in the Dictionary: ['Turkey', 'Damascus', 'Syria', 'Istanbul', 'China', 'Jerusalem']
---------------------------------------------------------
Key against Value 'China': Sa'd ibn Abi Waqqās (R.A.)
Key against Value 'Syria': Prophet Zulkuf (R.A.)
---------------------------------------------------------
---Approach II - Using OneLiner---
Key against Value 'China': Sa'd ibn Abi Waqqās (R.A.)
Key against Value 'Syria': Prophet Zulkuf (R.A.)
				
			
  • Example 2 – Search Element(s) from a Dictionary using Value
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Search Element(s) using Value
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to search element(s) using value
'''

try:
    # Approach I - Using Keys(), Values() and index()
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.70, 'Almond':1000.20, 'Pumpkin':60.75}   

    print("---Approach I - Using Keys(), Values() and index()---")

    # Store all Keys from the Dictionary in the Variable i.e., key_list
    key_list = list(products.keys())
    print("Keys in the Dictionary:", key_list)

    # Store all Values from the Dictionary in the Variable i.e., val_list
    val_list = list(products.values())
    print("Values in the Dictionary:", val_list)

    print("---------------------------------------------------------")

    # Store Index of Value '700.55' in a Variable i.e., position
    position_1 = val_list.index(700.55)
    # Display the Key with Value '700.55'
    print("Key against Value '700.55':",key_list[position_1])
 
    # Store Index of Value '3000.70' in a Variable i.e., position
    position_2 = val_list.index(3000.70)
    # Display the Key with Value '3000.70'
    print("Key against Value '3000.70':",key_list[position_2])
    
    print("---------------------------------------------------------")

    # Approach II - Using OneLiner
	
    print("---Approach II - Using OneLiner---")
    print("Key against Value '700.55':",list(products.keys())[list(products.values()).index(700.55)])
    print("Key against Value '3000.70':",list(products.keys())[list(products.values()).index(3000.70)])  
except Exception as ex:
    print(ex)

				
			
				
					---Approach I - Using Keys(), Values() and index()---
Keys in the Dictionary: ['Milk', 'Honey', 'Dates', 'Olive Oil', 'Almond', 'Pumpkin']
Values in the Dictionary: [150.15, 900.25, 700.55, 3000.7, 1000.2, 60.75]
---------------------------------------------------------
Key against Value '700.55': Dates
Key against Value '3000.70': Olive Oil
---------------------------------------------------------
---Approach II - Using OneLiner---
Key against Value '700.55': Dates
Key against Value '3000.70': Olive Oil
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Human Engineering’:

[‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Spiritual Training Courses’:

[‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Search from selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Search Element(s) from a Dictionary using key
      • Method 2: Search Element(s) from a Dictionary using value
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Search from selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Search Element(s) from a Dictionary using key
      • Method 2: Search Element(s) from a Dictionary using value

Operation 5 – Sorting

  • Methods to Sorting a Dictionary
  • In Sha Allah, in next Slides, I will present three methods of sorting a Dictionary
    • Method 1: Sorting a Dictionary by key-value pair
    • Method 2: Sorting a Dictionary by key
      • Method 2.1: Sorting a Dictionary by key in Ascending Order
      • Method 2.2: Sorting a Dictionary by key in Descending Order
    • Method 3: Sorting a Dictionary by value
      • Method 3.1: Sorting a Dictionary by value in Ascending Order
      • Method 3.2: Sorting a Dictionary by value in Descending Order

Sorting a Dictionary by key-value pair

  • Example 1 - Sorting a Dictionary by key-value pair
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key-value pair
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sort a dictionary by key-value pair
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7,'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Sorting---")
    print(products) 

    # Store key-value pair of a Dictionary using items() in Variable "dict_products"
    dict_products = products.items()

    # Sort Dictionary based on keys using sorted() Function
    sorted_dictionary = sorted(dict_products)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
[('Almond', 1000.2), ('Dates', 700.55), ('Honey', 900.25), ('Milk', 150.15), ('Olive Oil', 3000.7), ('Pumpkin', 60.75)]

				
			
  • Example 2 - Sorting a Dictionary by key-value pair
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key-value pair
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sort a dictionary by key-value pair
'''

try:
    tombs_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba) 

    '''
    Store key-value pair of a Dictionary using items() in Variable "dict_tombs_of_sahaba"
    '''
    dict_tombs_of_sahaba = tombs_of_sahaba.items()

    # Sort Dictionary based on keys using sorted() Function
    sorted_dictionary = sorted(dict_tombs_of_sahaba)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
[('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]

				
			

Sorting a Dictionary by key in Ascending Order

  • Example 1 - Sorting a Dictionary by key in Ascending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key in Ascending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by key in ascending order
'''

try:
    tombs_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba) 

    '''
    Store key-value pair of a Dictionary using items() in Variable "dict_tombs_of_sahaba"
    '''
    dict_tombs_of_sahaba = tombs_of_sahaba.items()

    # Sort Dictionary based on keys using sorted() Function
    # Sort Dictionary in Ascending Order using reverse = False
    sorted_dictionary = sorted(dict_tombs_of_sahaba, reverse = False)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
[('Abu Ayub Ansari (R.A.)', 'Turkey'), ('Bilal (R.A.)', 'Damascus'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Ubadah As-Samit (R.A.)', 'Jerusalem')]
				
			
  • Example 2 - Sorting a Dictionary by key in Ascending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key in Ascending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by key in ascending order
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7,'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Sorting---")
    print(products) 

    # Store key-value pair of a Dictionary using items() in Variable "dict_products"
    dict_products = products.items()

    # Sort Dictionary based on keys using sorted() Function
    # Sort Dictionary in Ascending Order using reverse = False
    sorted_dictionary = sorted(dict_products, reverse = False)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
[('Almond', 1000.2), ('Dates', 700.55), ('Honey', 900.25), ('Milk', 150.15), ('Olive Oil', 3000.7), ('Pumpkin', 60.75)]
				
			

Sorting a Dictionary by key in Descending Order

  • Example 1 - Sorting a Dictionary by key in Descending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key in Descending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by key in descending order
'''

try:
    tombs_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' , 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba) 

    '''
    Store key-value pair of a Dictionary using items() in Variable "dict_tombs_of_sahaba"
    '''
    dict_tombs_of_sahaba = tombs_of_sahaba.items()

    # Sort Dictionary based on keys using sorted() Function
    # Sort Dictionary in Descending Order using reverse = True
    sorted_dictionary = sorted(dict_tombs_of_sahaba, reverse = True)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
[('Ubadah As-Samit (R.A.)', 'Jerusalem'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Bilal (R.A.)', 'Damascus'), ('Abu Ayub Ansari (R.A.)', 'Turkey')]
				
			
  • Example 2 - Sorting a Dictionary by key in Descending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by key in Descending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by key in descending order
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7,'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Sorting---")
    print(products) 

    # Store key-value pair of a Dictionary using items() in Variable "dict_products"
    dict_products = products.items()

    # Sort Dictionary based on keys using sorted() Function
    # Sort Dictionary in Descending Order using reverse = True
    sorted_dictionary = sorted(dict_products, reverse = True)
    print("---New Dictionary after Sorting---")
    print(sorted_dictionary) 
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
[('Pumpkin', 60.75), ('Olive Oil', 3000.7), ('Milk', 150.15), ('Honey', 900.25), ('Dates', 700.55), ('Almond', 1000.2)]
				
			

Sorting a Dictionary by value in Ascending Order

  • Example 1 - Sorting a Dictionary by value in Ascending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by Value in Ascending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by value in ascending order
'''

try:

    # Approach I - Sort Dictionary using Lambda Function
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7,'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Approach I - Sort Dictionary using Lambda Function---")
    
    print("---Original Dictionary before Sorting---")
    print(products)

    # Sort our dictionary by value using lambda Function
    sort_orders = sorted(products.items(), key=lambda x: x[1], reverse=False)
    
    print("---New Dictionary after Sorting---")
    print(sort_orders)

    print("\n----------------------------------------------------------\n")

    # Approach II - Sort Dictionary using 'get'
    print("---Approach II - Sort Dictionary using 'get'---")

    print("---Original Dictionary before Sorting---")
    print(products)
    
    print("---New Dictionary after Sorting---")
    for w in sorted(products, key = products.get, reverse = False):
        print(w, products[w])
except:
    print("Error Occurred")

				
			
				
					---Approach I - Sort Dictionary using Lambda Function---
---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
[('Pumpkin', 60.75), ('Milk', 150.15), ('Dates', 700.55), ('Honey', 900.25), ('Almond', 1000.2), ('Olive Oil', 3000.7)]

----------------------------------------------------------

---Approach II - Sort Dictionary using 'get'---
---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
Olive Oil 3000.7
Almond 1000.2
Honey 900.25
Dates 700.55
Milk 150.15
Pumpkin 60.75
				
			
  • Example 2 - Sorting a Dictionary by value in Ascending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by Value in Ascending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by value in ascending order
'''

try:

    # Approach I - Sort Dictionary using Lambda Function
    tombs_of_sahaba = {'Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus', 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Approach I - Sort Dictionary using Lambda Function---")
    
    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba)

    # Sort our dictionary by value using lambda Function
    sort_orders = sorted(tombs_of_sahaba.items(), key=lambda x: x[1], reverse=False)
    
    print("---New Dictionary after Sorting---")
    print(sort_orders)

    print("\n----------------------------------------------------------\n")

    # Approach II - Sort Dictionary using 'get'
    print("---Approach II - Sort Dictionary using 'get'---")

    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba)
    
    print("---New Dictionary after Sorting---")
    for w in sorted(tombs_of_sahaba, key = tombs_of_sahaba.get, reverse = False):
        print(w, tombs_of_sahaba[w])
except:
    print("Error Occurred")

				
			
				
					---Approach I - Sort Dictionary using Lambda Function---
---Original Dictionary before Sorting---
{'Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
[('Saʿd ibn Abī Waqqās (R.A.)', 'China'), ('Bilal (R.A.)', 'Damascus'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Ubadah As-Samit (R.A.)', 'Jerusalem'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Ayub Ansari (R.A.)', 'Turkey')]

----------------------------------------------------------

---Approach II - Sort Dictionary using 'get'---
---Original Dictionary before Sorting---
{'Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
Saʿd ibn Abī Waqqās (R.A.) China
Bilal (R.A.) Damascus
Hazrat Jabir bin Abdullah (R.A.) Istanbul
Ubadah As-Samit (R.A.) Jerusalem
Prophet Zulkuf (R.A.) Syria
Ayub Ansari (R.A.) Turkey
				
			

Sorting a Dictionary by value in Descending Order

  • Example 1 - Sorting a Dictionary by value in Descending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by Value in Descending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by value in descending order
'''

try:

    # Approach I - Sort Dictionary using Lambda Function
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7,'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Approach I - Sort Dictionary using Lambda Function---")
    
    print("---Original Dictionary before Sorting---")
    print(products)

    # Sort our dictionary by value using lambda Function
    sort_orders = sorted(products.items(), key=lambda x: x[1], reverse=True)
    
    print("---New Dictionary after Sorting---")
    print(sort_orders)

    print("\n----------------------------------------------------------\n")

    # Approach II - Sort Dictionary using 'get'
    print("---Approach II - Sort Dictionary using 'get'---")

    print("---Original Dictionary before Sorting---")
    print(products)
    
    print("---New Dictionary after Sorting---")
    for w in sorted(products, key = products.get, reverse = True):
        print(w, products[w])
except:
    print("Error Occurred")

				
			
				
					---Approach I - Sort Dictionary using Lambda Function---
---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
[('Olive Oil', 3000.7), ('Almond', 1000.2), ('Honey', 900.25), ('Dates', 700.55), ('Milk', 150.15), ('Pumpkin', 60.75)]

----------------------------------------------------------

---Approach II - Sort Dictionary using 'get'---
---Original Dictionary before Sorting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Sorting---
Olive Oil 3000.7
Almond 1000.2
Honey 900.25
Dates 700.55
Milk 150.15
Pumpkin 60.75
				
			
  • Example 2 - Sorting a Dictionary by value in Descending Order
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Sorting a Dictionary by Value in Descending Order
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to sorting a dictionary by value in descending order
'''

try:

    # Approach I - Sort Dictionary using Lambda Function
    tombs_of_sahaba = {'Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus', 'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Approach I - Sort Dictionary using Lambda Function---")
    
    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba)

    # Sort our dictionary by value using lambda Function
    sort_orders = sorted(tombs_of_sahaba.items(), key=lambda x: x[1], reverse=True)
    
    print("---New Dictionary after Sorting---")
    print(sort_orders)

    print("\n----------------------------------------------------------\n")

    # Approach II - Sort Dictionary using 'get'
    print("---Approach II - Sort Dictionary using 'get'---")

    print("---Original Dictionary before Sorting---")
    print(tombs_of_sahaba)
    
    print("---New Dictionary after Sorting---")
    for w in sorted(tombs_of_sahaba, key = tombs_of_sahaba.get, reverse = True):
        print(w, tombs_of_sahaba[w])
except:
    print("Error Occurred")

				
			
				
					---Approach I - Sort Dictionary using Lambda Function---
---Original Dictionary before Sorting---
{'Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
[('Ayub Ansari (R.A.)', 'Turkey'), ('Prophet Zulkuf (R.A.)', 'Syria'), ('Ubadah As-Samit (R.A.)', 'Jerusalem'), ('Hazrat Jabir bin Abdullah (R.A.)', 'Istanbul'), ('Bilal (R.A.)', 'Damascus'), ('Saʿd ibn Abī Waqqās (R.A.)', 'China')]

----------------------------------------------------------

---Approach II - Sort Dictionary using 'get'---
---Original Dictionary before Sorting---
{'Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Sorting---
Ayub Ansari (R.A.) Turkey
Prophet Zulkuf (R.A.) Syria
Ubadah As-Samit (R.A.) Jerusalem
Hazrat Jabir bin Abdullah (R.A.) Istanbul
Bilal (R.A.) Damascus
Saʿd ibn Abī Waqqās (R.A.) China
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = { ‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’], ‘Human Engineering’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],
      • ‘Spiritual Training Courses’: [‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}
  • Questions
    • Sort the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Sorting a Dictionary by key-value pair
      • Method 2: Sorting a Dictionary by key
        • Method 2.1: Sorting a Dictionary by key in Ascending Order
        • Method 2.2: Sorting a Dictionary by key in Descending Order
      • Method 3: Sorting a Dictionary by value
        • Method 3.1: Sorting a Dictionary by value in Ascending Order
        • Method 3.2: Sorting a Dictionary by value in Descending Order
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Sort the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Sorting a Dictionary by key-value pair
      • Method 2: Sorting a Dictionary by key
        • Method 2.1: Sorting a Dictionary by key in Ascending Order
        • Method 2.2: Sorting a Dictionary by key in Descending Order
      • Method 3: Sorting a Dictionary by value
        • Method 3.1: Sorting a Dictionary by value in Ascending Order
        • Method 3.2: Sorting a Dictionary by value in Descending Order

Operation 6 – Merging

  • Methods of Merging Dictionaries
  • In Sha Allah, in next Slides, I will present two methods to merge / concatenate Dictionaries
    • Method 1: Concatenate Dictionaries using update() Function
    • Method 2: Concatenate Dictionaries using ** Operators

Concatenate Dictionaries using update() Function

  • Example 1 – Concatenate Lists - Using + Operator
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Concatenate Dictionaries using update() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to concatenate dictionaries using update() function 
'''

try:
    dict1_tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China','Ubadah As-Samit (R.A.)': 'Jerusalem'}

    dict2_tombs_of_sahaba = { 
    'Hazrat Abuzer Gifari (R.A.)' : 'Istanbul', 'Hazrat Eyub (R.A.)' : 'Istanbul','Abu Darda (R.A.)' : 'Turkey', 'Hazrat Abdulvedud (R.A.)' : 'Istanbul', 'Hazrat Kaabe (R.A.)' : 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)' : 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)' : 'Istanbul'}

    
    print("---Original Dictionary before Merge---")
    print("dict1_tombs_of_sahaba", dict1_tombs_of_sahaba)
    print("dict2_tombs_of_sahaba", dict2_tombs_of_sahaba)

    # Use update() Function to merge two Dictionaries
    dict1_tombs_of_sahaba.update(dict2_tombs_of_sahaba)

    print("---New Dictionary after Merge---")
    print(dict1_tombs_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Merge---
dict1_tombs_of_sahaba {'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
dict2_tombs_of_sahaba {'Hazrat Abuzer Gifari (R.A.)': 'Istanbul', 'Hazrat Eyub (R.A.)': 'Istanbul', 'Abu Darda (R.A.)': 'Turkey', 'Hazrat Abdulvedud (R.A.)': 'Istanbul', 'Hazrat Kaabe (R.A.)': 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)': 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)': 'Istanbul'}
---New Dictionary after Merge---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem', 'Hazrat Abuzer Gifari (R.A.)': 'Istanbul', 'Hazrat Eyub (R.A.)': 'Istanbul', 'Abu Darda (R.A.)': 'Turkey', 'Hazrat Abdulvedud (R.A.)': 'Istanbul', 'Hazrat Kaabe (R.A.)': 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)': 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)': 'Istanbul'}
				
			
  • Example 2 - Concatenate Dictionaries using update() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Concatenate Dictionaries using update() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to concatenate dictionaries using update() function 
'''

try:
    dict1_products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    dict2_products = {'Chocolates':'150.0', 'Cakes':'1000.5', 'Brownies':'300.25'}
    
    print("---Original Dictionary before Merge---")
    print("dict1_products", dict1_products)
    print("dict2_products", dict2_products)

    # Use update() Function to merge two Dictionaries
    dict1_products.update(dict2_products)

    print("---New Dictionary after Merge---")
    print(dict1_products)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Merge---
dict1_products {'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
dict2_products {'Chocolates': '150.0', 'Cakes': '1000.5', 'Brownies': '300.25'}
---New Dictionary after Merge---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75, 'Chocolates': '150.0', 'Cakes': '1000.5', 'Brownies': '300.25'}
				
			

Concatenate Dictionaries using ** Operator

  • Example 1 - Concatenate Dictionaries using ** Operator
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Concatenate Dictionaries using ** Operator
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to concatenate dictionaries using ** operator 
'''

try:
    dict1_tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China','Ubadah As-Samit (R.A.)': 'Jerusalem'}

    dict2_tombs_of_sahaba = { 
    'Hazrat Abuzer Gifari (R.A.)' : 'Istanbul', 'Hazrat Eyub (R.A.)' : 'Istanbul','Abu Darda (R.A.)' : 'Turkey', 'Hazrat Abdulvedud (R.A.)' : 'Istanbul', 'Hazrat Kaabe (R.A.)' : 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)' : 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)' : 'Istanbul'}

    
    print("---Original Dictionary before Merge---")
    print("dict1_tombs_of_sahaba", dict1_tombs_of_sahaba)
    print("dict2_tombs_of_sahaba", dict2_tombs_of_sahaba)

    # Use ** Operator to merge two Dictionaries
    dict3_tombs_of_sahaba = dict(dict1_tombs_of_sahaba,** dict2_tombs_of_sahaba)
    
    print("---New Dictionary after Merge---")
    print(dict3_tombs_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Merge---
dict1_tombs_of_sahaba {'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
dict2_tombs_of_sahaba {'Hazrat Abuzer Gifari (R.A.)': 'Istanbul', 'Hazrat Eyub (R.A.)': 'Istanbul', 'Abu Darda (R.A.)': 'Turkey', 'Hazrat Abdulvedud (R.A.)': 'Istanbul', 'Hazrat Kaabe (R.A.)': 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)': 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)': 'Istanbul'}
---New Dictionary after Merge---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem', 'Hazrat Abuzer Gifari (R.A.)': 'Istanbul', 'Hazrat Eyub (R.A.)': 'Istanbul', 'Abu Darda (R.A.)': 'Turkey', 'Hazrat Abdulvedud (R.A.)': 'Istanbul', 'Hazrat Kaabe (R.A.)': 'Istanbul', 'Hazrat Abdul Sadiq bin Amir (R.A.)': 'Istanbul', 'Hazrat Muhammed el-Ensari (R.A.)': 'Istanbul'}
				
			
  • Example 2 - Concatenate Dictionaries using ** Operator
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Concatenate Dictionaries using ** Operator
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 
the main purpose of the program is to concatenate dictionaries using ** operator 
'''

try:
    dict1_products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    dict2_products = {'Chocolates':'150.0', 'Cakes':'1000.5', 'Brownies':'300.25'}
    
    print("---Original Dictionary before Merge---")
    print("dict1_products", dict1_products)
    print("dict2_products", dict2_products)

    # Use ** Operator Function to merge two Dictionaries
    dict3_products = dict(dict1_products,** dict2_products)

    print("---New Dictionary after Merge---")
    print(dict3_products)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Merge---
dict1_products {'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
dict2_products {'Chocolates': '150.0', 'Cakes': '1000.5', 'Brownies': '300.25'}
---New Dictionary after Merge---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75, 'Chocolates': '150.0', 'Cakes': '1000.5', 'Brownies': '300.25'}
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Human Engineering’:

[‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Spiritual Training Courses’:

[‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Merge the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Concatenate Dictionaries using update() Function
      • Method 2: Concatenate Dictionaries using ** Operators
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Merge the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Concatenate Dictionaries using update() Function
      • Method 2: Concatenate Dictionaries using ** Operators

Operation 7 – Updation

  • Methods of Updating a Dictionary
  • In Sha Allah, in next Slides, I will present three methods to update a Dictionary
    • Method 1: Update the key of a Dictionary using pop() Function
    • Method 2: Update the value of a Dictionary
    • Method 3: Update the value of a Dictionary using update() Function

Update the key of a Dictionary using pop() Function

  • Example 1 – Update the key of a Dictionary using pop() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Update the key of a Dictionary using pop() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to update the key of a dictionary using pop() function
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China','Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Updatation---")
    print(tombs_of_sahaba)

    # Use pop() Function to update old_key_value with new_key_value
    new_key = "Abdullah ibn Abbas (R.A.)"
    old_key = "Abu Ayub Ansari (R.A.)"
    tombs_of_sahaba[new_key] = tombs_of_sahaba.pop(old_key)

    print("---New Dictionary after Updatation---")
    print(tombs_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Updatation---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Updatation---
{'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem', 'Abdullah ibn Abbas (R.A.)': 'Turkey'}
				
			
  • Example 2 – Update the key of a Dictionary using pop() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Update the key of a Dictionary using pop() Function
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to update the key of a dictionary using pop() function
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Updatation---")
    print(products)

    # Use pop() Function to update old_key_value with new_key_value
    new_key = "Mango"
    old_key = "Milk"
    products[new_key] = products.pop(old_key)

    print("---New Dictionary after Updatation---")
    print(products)
except:
    print("Error Occurred")
				
			
				
					---Original Dictionary before Updatation---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Updatation---
{'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75, 'Mango': 150.15}

				
			

Update the value of a Dictionary

  • Example 1 – Update the value of a Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Update the value of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to update the value of a dictionary
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China','Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Updatation---")
    print(tombs_of_sahaba)

    # Use key for updating value in a Dictionary
    tombs_of_sahaba["Hazrat Jabir bin Abdullah (R.A.)"] = "Turkey"
    
    print("---New Dictionary after Updatation---")
    print(tombs_of_sahaba)
except:
    print("Error Occurred")

				
			
				
					---Original Dictionary before Updatation---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Updatation---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Turkey', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
				
			
  • Example 2 – Update the value of a Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Update the value of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to update the value of a dictionary
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    print("---Original Dictionary before Updatation---")
    print(products)

    # Use key for updating value in a Dictionary
    products["Pumpkin"] = "90.45"
    
    print("---New Dictionary after Updatation---")
    print(products)
except:
    print("Error Occurred")
				
			
				
					---Original Dictionary before Updatation---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Updatation---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': '90.45'}
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {

‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Human Engineering’:

[‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

‘Spiritual Training Courses’:

[‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Update the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Update the key of a Dictionary using pop() Function
      • Method 2: Update the value of a Dictionary
      • Method 3: Update the value of a Dictionary using update() Function
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Update the selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Update the key of a Dictionary using pop() Function
      • Method 2: Update the value of a Dictionary
      • Method 3: Update the value of a Dictionary using update() Function

Operation 8 – Deletion

  • Methods to Delete Element(s) from a Dictionary
  • In Sha Allah, in next Slides, I will present four methods to delete a Dictionary
    • Method 1: Delete Entire / Element(s) from a Dictionary using del
    • Method 2: Remove Element(s) of a Dictionary using clear() Function
    • Method 3: Remove Specific Element(s) from a Dictionary using pop() Function
    • Method 4: Remove Last Element(s) from a Dictionary using popitem() Function

Delete Entire / Element(s) from a Dictionary using del

  • Example 1 – Delete Entire Tuple - Using del
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Delete Entire / Element(s) from a Dictionary using del
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to Delete Entire / Element(s) from a Dictionary using del 
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
    
    # Approach I - Delete Specific Element from Dictionary
    print("---Approach I - Delete Specific Element from Dictionary---")
    
    print("---Original Dictionary before Deleting---")
    print(products)

    # Use del to delete specific key-value pair from a Dictionary
    del products['Almond']
    
    print("---New Dictionary after Deleting---")
    print(products)
    
    print("----------------------------------------------")
    
    # Approach II - Delete Entire Dictionary
    print("---Approach II - Delete Entire Dictionary---")
    
    print("---Original Dictionary before Deleting---")
    print(products)

    # Use del to delete specific key-value pair from a Dictionary
    del products
    
    print("---New Dictionary after Deleting---")
    print(products)
except Exception as ex:
    print(ex)

				
			
				
					---Approach I - Delete Specific Element from Dictionary---
---Original Dictionary before Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Pumpkin': 60.75}
----------------------------------------------
---Approach II - Delete Entire Dictionary---
---Original Dictionary before Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Pumpkin': 60.75}
---New Dictionary after Deleting---
name 'products' is not defined
				
			
  • Example 2 - Delete Entire / Element(s) from a Dictionary using del
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Delete Entire / Element(s) from a Dictionary using del
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to Delete Entire / Element(s) from a Dictionary using del 
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    

    # Approach I - Delete Specific Element from Dictionary
    print("---Approach I - Delete Specific Element from Dictionary---")
    
    print("---Original Dictionary before Deleting---")
    print(tombs_of_sahaba)

    # Use del to delete specific key-value pair from a Dictionary
    del tombs_of_sahaba['Prophet Zulkuf (R.A.)']
    
    print("---New Dictionary after Deleting---")
    print(tombs_of_sahaba)
    
    print("----------------------------------------------")
    
    # Approach II - Delete Entire Dictionary
    print("---Approach II - Delete Entire Dictionary---")
    
    print("---Original Dictionary before Deleting---")
    print(tombs_of_sahaba)

    # Use del to delete specific key-value pair from a Dictionary
    del tombs_of_sahaba
    
    print("---New Dictionary after Deleting---")
    print(tombs_of_sahaba)
except Exception as ex:
    print(ex)

				
			
				
					---Approach I - Delete Specific Element from Dictionary---
---Original Dictionary before Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
----------------------------------------------
---Approach II - Delete Enitre Dictionary---
---Original Dictionary before Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Deleting---
name 'tombs_of_sahaba' is not defined
				
			

Remove Elements of a Dictionary using clear() Function

  • Example 1 - Remove Elements of a Dictionary using clear() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove Elements of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove elements of a dictionary using clear() function
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
 
    print("---Original Dictionary before Deleting---")
    print(products)

    # Use clear() Function to delete all elements of a Dictionary
    products.clear()
    
    print("---New Dictionary after Deleting---")
    print(products)
except Exception as ex:
    print(ex)

				
			
				
					---Original Dictionary before Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Deleting---
{}
				
			
  • Example 2 - Remove Elements of a Dictionary using clear() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove Elements of a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove elements of a dictionary using clear() function
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Deleting---")
    print(tombs_of_sahaba)

    # Use clear() Function to delete all elements of a Dictionary    
    tombs_of_sahaba.clear()
    
    print("---New Dictionary after Deleting---")
    print(tombs_of_sahaba)
except Exception as ex:
    print(ex)

				
			
				
					---Original Dictionary before Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Deleting---
{}
				
			

Remove Specific Element(s) from a Dictionary using pop() Function

  • Example 1 - Remove Specific Element(s) from a Dictionary using pop() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove specific Element(s) from a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove specific element(s) of a dictionary using pop() function
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
 
    print("---Original Dictionary before Deleting---")
    print(products)

    # Use pop() Function to remove specific element(s) of a Dictionary
    products.pop('Honey')
    
    print("---New Dictionary after Deleting---")
    print(products)
except Exception as ex:
    print(ex)
				
			
				
					---Original Dictionary before Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Deleting---
{'Milk': 150.15, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
				
			
  • Example 2 - Remove Specific Element(s) from a Dictionary using pop() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove specific Element(s) from a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove specific element(s) of a dictionary using pop() function
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Deleting---")
    print(tombs_of_sahaba)

    # Use pop () Function to remove specific element(s) of a Dictionary
    tombs_of_sahaba.pop('Saʿd ibn Abī Waqqās (R.A.)')
    
    print("---New Dictionary after Deleting---")
    print(tombs_of_sahaba)
except Exception as ex:
    print(ex)

				
			
				
					---Original Dictionary before Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
				
			

Remove Last Element(s) from a Dictionary using popitem() Function

  • Example 1 - Remove Last Element(s) from a Dictionary using popitem() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove Last Element(s) from a Dictionary
programming_language 	= Python	
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove last element(s) of a dictionary using popitem() function
'''

try:
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}
 
    print("---Original Dictionary before Deleting---")
    print(products)

    # Use popitem() Function to remove last element(s) of a Dictionary
    products.popitem()
    
    print("---New Dictionary after Deleting---")
    print(products)
except Exception as ex:
    print(ex)

				
			
				
					---Original Dictionary before Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2, 'Pumpkin': 60.75}
---New Dictionary after Deleting---
{'Milk': 150.15, 'Honey': 900.25, 'Dates': 700.55, 'Olive Oil': 3000.7, 'Almond': 1000.2}
				
			
  • Example 2 - Remove Last Element(s) from a Dictionary using popitem() Function
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove Last Element(s) from a Dictionary
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to remove last element(s) of a dictionary using popitem() function
'''

try:
    tombs_of_sahaba = { 'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
    
    print("---Original Dictionary before Deleting---")
    print(tombs_of_sahaba)

    # Use popitem() Function to remove last element(s) of a Dictionary    
    tombs_of_sahaba.popitem()
    
    print("---New Dictionary after Deleting---")
    print(tombs_of_sahaba)
except Exception as ex:
    print(ex)

				
			
				
					---Original Dictionary before Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
---New Dictionary after Deleting---
{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China'}

				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
      • courses = {
    • ‘Python’: [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

      ‘Human Engineering’:

      [‘Samavi’,’Narmeen’,’Awais’,’Rehan’,’Hassan’,’Hassan’],

      ‘Spiritual Training Courses’:

      [‘Rehan’,’Awais’,’Ali’,’Ahmed’,’Sara’,’Zara’,’Mahnoor’, ‘Maira’]}

  • Questions
    • Remove from selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Delete Entire / Element(s) from a Dictionary using del
      • Method 2: Remove Element(s) of a Dictionary using clear() Function
      • Method 3: Remove Specific Element(s) from a Dictionary using pop() Function
      • Method 4: Remove Last Element(s) from a Dictionary using popitem() Function
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider two Dictionaries (similar to the ones given in TODO Task 1) and answer the questions given below
  • Questions
    • Search from selected Dictionaries using following methods (as shown in this Chapter)
      • Method 1: Search Element(s) from a Dictionary using key
      • Method 2: Search Element(s) from a Dictionary using value

Dictionary Comprehension

  • Dictionary Comprehension
  • Definition
    • Dictionary comprehension is a simple method for (conditionally) transforming items of one dictionary into another dictionary without using loops
  • Syntax
				
					dictionary = {key: value for vars in iterable}
				
			
  • Example 1 - Dictionary Comprehension
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Dictionary Comprehension
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to create a new dictionary based on key-value pairs of an existing dictionary
'''

try:
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}

    # Create a new dictionary with element of previous dictionary
    new_price = {item: value * 0.25 for (item, value) in products.items()}  
    print(new_price)
except Exception as ex:
    print(ex)
				
			
				
					{'Milk': 37.5375, 'Honey': 225.0625, 'Dates': 175.1375, 'Olive Oil': 750.175, 'Almond': 250.05, 'Pumpkin': 15.1875}
				
			
  • Example 2 - Dictionary Comprehension
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Dictionary Comprehension
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to create a new dictionary based on key-value pairs of an existing dictionary
'''

try:
    # Dictionary Initialization
    products = {'Milk':150.15, 'Honey':900.25, 'Dates':700.55, 'Olive Oil':3000.7, 'Almond':1000.2, 'Pumpkin':60.75}

    # Create a new dictionary with element of previous dictionary
    new_price = {key: ('Even' if value % 2 == 0 else 'Odd')
    for (key, value) in products.items()}
    print(new_price)
except Exception as ex:
    print(ex)

				
			
				
					{'Milk': 'Odd', 'Honey': 'Odd', 'Dates': 'Odd', 'Olive Oil': 'Odd', 'Almond': 'Odd', 'Pumpkin': 'Odd'}
				
			
  • Example 3 - Dictionary Comprehension
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Dictionary Comprehension
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to create a new dictionary based on key-value pairs of an existing dictionary
'''


try:
    # Dictionary Initialization
    tombs_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Create a new dictionary with element of previous dictionary
    new_price = {item: value for (item, value) in tombs_of_sahaba.items()
    if "i" in item}     
    print(new_price)
except Exception as ex:
    print(ex)
				
			
				
					{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
				
			
  • Example 4 - Dictionary Comprehension
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Dictionary Comprehension
programming_language 	= Python
operating_system  	= Windows 10 
ide 				= Jupyter Notebook
licence 			= public_domain_1.0
start_date 		      = 21-Jun-2022
end_data 			= 21-Jun-2022
'''

'''
Purpose of Program 	
The main purpose of the program is to create a new dictionary based on key-value pairs of an existing dictionary
'''


try:
    # Dictionary Initialization
    tombs_of_sahaba = {'Abu Ayub Ansari (R.A.)' : 'Turkey', 'Bilal (R.A.)' : 'Damascus' ,'Prophet Zulkuf (R.A.)' : 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)' : 'Istanbul','Saʿd ibn Abī Waqqās (R.A.)' : 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}

    # Create a new dictionary with element of previous dictionary
    new_price = {item: value for (item, value) in tombs_of_sahaba.items()}     
    print(new_price)
except Exception as ex:
    print(ex)

				
			
				
					{'Abu Ayub Ansari (R.A.)': 'Turkey', 'Bilal (R.A.)': 'Damascus', 'Prophet Zulkuf (R.A.)': 'Syria', 'Hazrat Jabir bin Abdullah (R.A.)': 'Istanbul', 'Saʿd ibn Abī Waqqās (R.A.)': 'China', 'Ubadah As-Samit (R.A.)': 'Jerusalem'}
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following two Dictionaries and answer the questions given below
      • phone_directory = {‘0348-6642185’: ‘Adeeb’, ‘0321-4971961′:’Saaliha’, ‘0321-5865463’: ‘Kamaal’, ‘0321-4582322’: ‘Naaila’, ‘0345-8071517’: ‘Zuhra’, ‘0323-7654151′:’Wajeeha’}
  • Questions
    • Use phone_directory to create a new dictionary which contains numbers starting with 0321?
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider a Dictionary (similar to the one given in TODO Task 1) and answer the questions given below
  • Questions
    • Use the concept of Dictionary Comprehension to create a new Dictionary based on the selected Dictionary?

Nested Dictionary

  • Nested Dictionary
  • The syntax to create a Nested Dictionary using {} is as follows

Creating a Nested Dictionary

  • Syntax - Creating a Nested Dictionary
  • The syntax to create a Nested Tuple using () is as follows
				
					nested_dict = { 
      'dictA': {'key_1': 'value_1'},
      'dictB': {'key_2': 'value_2'},
      'dictC': {'key_3': 'value_3'},
      'dictD': {'key_4': 'value_4'},
                 .
                 .
                 .
      'dictN': {'key_N': 'value_N'},
      }
				
			
  • Example 1 - Creating a Nested Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Create a Nested Dictionary 
programming_language 	= Python
operating_system      = Windows 10 
ide                   = Jupyter Notebook
licence               = public_domain_1.0
start_date            = 21-Jun-2022
end_date              = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to create a nested dictionary
'''

# Initializing a Nested Dictionary i.e., students

try:
    students = {1: {'Name': 'Samavi', 'Age': '27', 'Gender': 'Female'},
          2: {'Name': 'Umer', 'Age': '22', 'Gender': 'Male'}}

    print("Dictionary of Students for Introduction to Python:\n", students)
    
    # Data-Type of Dictionary i.e., students
    print("Data-Type of students:", type(students))
    
    # Length of Dictionary i.e., students
    print("Length of students:", len(students))
except:
    print("Error Occurred")
				
			
				
					Dictionary of Students for Introduction to Python:
 {1: {'Name': 'Samavi', 'Age': '27', 'Gender': 'Female'}, 2: {'Name': 'Umer', 'Age': '22', 'Gender': 'Male'}}
Data-Type of students: <class 'dict'>
Length of students: 2

				
			
  • Example 2 - Creating a Nested Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Create a Nested Dictionary 
programming_language 	= Python
operating_system      = Windows 10 
ide                   = Jupyter Notebook
licence               = public_domain_1.0
start_date            = 21-Jun-2022
end_date              = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to create a nested dictionary
'''

# Initializing a Nested Dictionary i.e., course_registration

try:
    course_registration = { 
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'},
    2: {'Student_Name': 'Ms. Sana','Gender': 'Female', 'Age': '23','City': 'Karachi'},
    3:{'Student_Name': 'Mr. Ali','Gender': 'Male', 'Age': '28','City': 'Islamabad'},
    4:{'Student_Name': 'Mr. Ahmed','Gender': 'Male', 'Age': '26','City': 'Gujrat'},
    5:{'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Gujranwala'},
    }

    print("Dictionary of Students Registered for Introduction to Python:\n", course_registration)
    
    # Data-Type of Dictionary i.e., students
    print("Data-Type of course_registration:", type(course_registration))
    
    # Length of Dictionary i.e., students
    print("Length of course_registration:", len(course_registration))
except:
    print("Error Occurred")

				
			
				
					Dictionary of Students Registered for Introduction to Python:
 {1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Sana', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}, 3: {'Student_Name': 'Mr. Ali', 'Gender': 'Male', 'Age': '28', 'City': 'Islamabad'}, 4: {'Student_Name': 'Mr. Ahmed', 'Gender': 'Male', 'Age': '26', 'City': 'Gujrat'}, 5: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Gujranwala'}}
Data-Type of course_registration: <class 'dict'>
Length of course_registration: 5

				
			

Access Elements of a Nested Dictionary

  • Access Elements of a Nested Dictionary
  • You can access individual items in a Nested Dictionary using multiple indexes
  • Example 1 - Access Elements of a Nested Dictionary – Using Indexing
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Access Elements of Nested Dictionary 
programming_language 	= Python
operating_system     = Windows 10 
ide 			     = Jupyter Notebook
licence 		     = public_domain_1.0
start_date 	     = 21-Jun-2022
end_date 		     = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to access elements of a nested dictionary
'''

# Approach I - Access Elements of a Nested Dictionary – Using Indexing
try:
    # Nested Dictionary Initialization
    student_information = {
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'}, 
    2: {'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Karachi'}}

    print("---Approach I - Access Elements of a Nested Dictionary – Using Indexing---")

    # Access Elements of Nested Dictionary using Indexing
    print("Element at index student_information[1] with Key 'Student_Name':",
student_information[1]['Student_Name'])
    
    print("Element at index student_information[1] with Key 'Gender':",
student_information[1]['Gender'])
    
    print("Element at index student_information[1] with Key 'Age':",
student_information[1]['Age'])
    
    print("Element at index student_information[1] with Key 'City':",
student_information[1]['City'])

    print("---------------------------------------------------------")

     # Approach II - Access Elements of Nested Dictionary using another Dictionary

    print("---Approach II - Access Elements of Nested Dictionary using another Dictionary---")

    # Access Elements of Nested Dictionary using another Dictionary
    student_information[3] = {}
    
    # Add Values in a new Dictionary 
    student_information[3]['Student_Name'] = 'Mr. Imran'
    student_information[3]['Gender'] = 'Male'
    student_information[3]['Age'] = '20'
    student_information[3]['City'] = 'Multan'
    
    # Display the New Dictionary
    print("Access New Dictionary:\n",student_information[3])
except:
    print("Error Occurred")

				
			
Memory Representation
				
					Element at index student_information[1] with Key 'Student_Name': Ms. Samavi
Element at index student_information[1] with Key 'Gender': Female
Element at index student_information[1] with Key 'Age': 24
Element at index student_information[1] with Key 'City': Lahore
				
			

Operations on Nested Dictionary

  • Add Elements in a Nested Dictionary
  • In Sha Allah, in next Slides, I will present a method to add element(s) in a Nested Dictionary
    • Method 1 – Add a New Dictionary inside a Nested Dictionary
  • Example 1 - Add Elements in a Nested Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Add Elements in a Nested Dictionary
programming_language 	= Python
operating_system     = Windows 10 
ide 			     = Jupyter Notebook
licence 		     = public_domain_1.0
start_date 	     = 21-Jun-2022
end_date 		     = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to add elements in a nested dictionary
'''

# Initializing a Nested Dictionary i.e., student_information

try:
    student_information = {
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'},
    2: {'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Karachi'}}
    
    # Display Original Dictionary
    print("---Original Nested Dictionary---")
    print(student_information)

    # Display Dictionary after Adding a New Dictionary inside a Nested Dictionary
    print("---New Dictionary adding a Dictionary---")

    # Create a Key-Value Pair i.e., another Dictionary inside a Dictionary
    student_information[3] = {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}

    print(student_information)
except:
    print("Error Occurred")

				
			
				
					---Original Nested Dictionary---
{1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}}
---New Dictionary adding a Dictionary---
{1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}, 3: {'name': 'Peter', 'age': '29', 'sex': 'Male', 'married': 'Yes'}}
				
			

Traverse a Nested Dictionary

  • Traverse a Nested Dictionary
  • In Sha Allah, in next Slides, I will present a method to traverse a Dictionary
    • Method 1: Traversing a Nested Dictionary (Element by Element)
  • Example 1 - Traversing a Nested Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Traversing a Dictionary
programming_language 	= Python
operating_system     = Windows 10 
ide 			     = Jupyter Notebook
licence 		     = public_domain_1.0
start_date 	     = 21-Jun-2022
end_date 		     = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to traversing a dictionary
'''

# Initializing a Nested Dictionary i.e., student_information

try:
    student_information = {
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'},
    2: {'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Karachi'},
    3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20',  'City': 'Multan'}}

    # Traverse a Dictionary
    for student_id, student_info in student_information.items():
        print("\nStudent_ID:", student_id)
        for key in student_info:
            print(key + ':', student_info[key])
except:
    print("Error Occurred")

				
			
				
					Student_ID: 1
Student_Name: Ms. Samavi
Gender: Female
Age: 24
City: Lahore

Student_ID: 2
Student_Name: Ms. Samra
Gender: Female
Age: 23
City: Karachi

Student_ID: 3
Student_Name: Mr. Imran
Gender: Male
Age: 20
City: Multan
				
			

Remove Elements from a Nested Dictionary

  • Remove Elements from a Nested Tuple
  • In Sha Allah, in next Slides, I will present two methods to remove element(s) in a Nested Dictionary
    • Method 1 – Remove Element(s) of a Nested Dictionary
    • Method 2 – Remove Entire Dictionary
  • Example 1 - Remove Element(s) from a Nested Dictionary
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Remove Elements from a Nested Dictionary
programming_language 	= Python
operating_system     = Windows 10 
ide 			     = Jupyter Notebook
licence 		     = public_domain_1.0
start_date 	     = 21-Jun-2022
end_date 		     = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to remove elements from a nested dictionary
'''

try:
    student_information = {
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'},
    2: {'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Karachi'},
    3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20',  'City': 'Multan'}}

    # Approach I – Remove a Key from a Nested Dictionary
    print("---Approach I – Remove an Key from a Nested Dictionary---")
    
    # Display Original Dictionary
    print("---Original Nested Dictionary---")
    print(student_information)   

    # Remove Key at Index 2
    del student_information[3]['City']

    print("---New Dictionary after Removing a Key from a Nested Dictionary---")
    print(student_information)

    # Approach II – Remove a Nested Dictionary
    print("---Approach II – Remove a Nested Dictionary---")
    
    # Display Original Dictionary
    print("---Original Nested Dictionary---")
    print(student_information)   

    # Remove a Dictionary
    del student_information

    print("---New Dictionary after Removing a Nested Dictionary---")
    print(student_information)
except Exception as ex:
    print(ex)

				
			
				
					---Approach I – Remove an Key from a Nested Dictionary---
---Original Nested Dictionary ---
{1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}, 3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20', 'City': 'Multan'}}
---New Dictionary after Removing a Key from a Nested Dictionary---
{1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}, 3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20'}}
---Approach II – Remove a Nested Dictionary---
---Original Nested Dictionary ---
{1: {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}, 2: {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}, 3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20'}}
---New Dictionary after Removing a Nested Dictionary---
name 'student_information' is not defined
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following Nested Dictionary and answer the questions given below

student_courses = {

‘FA15-BCS-01’:

{‘Program’:’BS(CS)’,’Degree’:’Bachelors in Computer Science’},

‘FA15-BCS-03’:

{‘Program’:’BS(CE)’,’Degree’:’Bachelors in Computer Science’},

‘FA15-BCS-05’:

{‘Program’:’BS(CS)’,’Degree’:’Bachelors in Computer Science’}}

  • Questions
    • Apply following operations on the given Nested Dictionary (as shown in this Chapter)?
      • Operation 1: Create a Nested Dictionary
      • Operation 2: Access Elements of a Nested Dictionary
      • Operation 3: Add New Element in a Nested Dictionary
      • Operation 4: Traverse a Nested Dictionary
      • Operation 6: Remove Elements of a Nested Dictionary
  •  
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider a Nested Dictionary (similar to the one given in TODO Task 1) and answer the questions given below
  • Questions
    • Apply following operations on the selected Nested Dictionary (as shown in this Chapter)?
      • Operation 1: Create a Nested Dictionary
      • Operation 2: Access Elements of a Nested Dictionary
      • Operation 3: Add New Element in a Nested Dictionary
      • Operation 4: Traverse a Nested Dictionary
      • Operation 6: Remove Elements of a Nested Dictionary

Creating a Dictionary within a List

  • Example 1 - Creating a Dictionary within a List
				
					'''
Author and System Information 
author_name 		= Ms. Samavi Salman
program_name 		= Creating a Dictionary within a List
programming_language 	= Python
operating_system     = Windows 10 
ide 			     = Jupyter Notebook
licence 		     = public_domain_1.0
start_date 	     = 21-Jun-2022
end_date 		     = 21-Jun-2022
'''

'''
Purpose of Program 
The main purpose of the program is to create a dictionary within a list
'''


try:
    course_registration = {
    'Learn How to Achieve Excellence in Love and Obedience of Allah': 
    [{'Student_Name': 'Ms. Samavi'},{'Gender': 'Female'}, {'Age': '24'},  {'City': 'Lahore'},
      {'Student_Name': 'Ms. Sana'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Karachi'},
     {'Student_Name': 'Mr. Ali'},{'Gender': 'Male'}, {'Age': '28'},{'City': 'Islamabad'},
     {'Student_Name': 'Mr. Ahmed'},{'Gender': 'Male'}, {'Age': '26'},{'City': 'Gujrat'},
     {'Student_Name': 'Ms. Samra'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Gujranwala'},
     {'Student_Name': 'Mr. Mustafa'},{'Gender': 'Male'}, {'Age': '28'},{'City': 'Multan'}
    ],
    'Learn How to Achieve Excellence in Love and Obedience of Hazrat Muhammad (PBUH)': 
    [{'Student_Name': 'Ms. Fatima'},{'Gender': 'Female'}, {'Age': '22'},{'City': 'Lahore'},
      {'Student_Name': 'Ms. Samra'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Karachi'},
     {'Student_Name': 'Mr. Rizwan'},{'Gender': 'Male'}, {'Age': '25'},{'City': 'Lahore'},
     {'Student_Name': 'Mr. Ahmed'},{'Gender': 'Male'}, {'Age': '26'},{'City': 'Karachi'},
     {'Student_Name': 'Ms. Saman'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Lahore'},
     {'Student_Name': 'Mr. Abdullah'},{'Gender': 'Male'}, {'Age': '28'},{'City': 'Lahore'}
    ],
    'Learn How to Become an Authority in Your Field':
    [{'Student_Name': 'Ms. Ayesha'},{'Gender': 'Female'}, {'Age': '24'},{'City': 'Lahore'},
     {'Student_Name': 'Mr. Umer'},{'Gender': 'Male'}, {'Age': '21'},{'City': 'Lahore'},
     {'Student_Name': 'Ms. Sana'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Islamabad'},
     {'Student_Name': 'Mr. Ali'},{'Gender': 'Male'}, {'Age': '28'},{'City': 'Lahore'},
      {'Student_Name': 'Ms. Sana'},{'Gender': 'Female'}, {'Age': '23'},{'City': 'Lahore'},
     {'Student_Name': 'Mr. Ali'},{'Gender': 'Male'}, {'Age': '28'},{'City': 'Lahore'},
     {'Student_Name': 'Mr. Ahmed'},{'Gender': 'Male'}, {'Age': '26'},{'City': 'Lahore'}
    ],
}
    print("Creating a Dictionary within a List:\n",course_registration)

except Exception as ex:
    print(ex)

				
			
				
					Creating a Dictionary within a List:
 {'Learn How to Achieve Excellence in Love and Obedience of Allah': [{'Student_Name': 'Ms. Samavi'}, {'Gender': 'Female'}, {'Age': '24'}, {'City': 'Lahore'}, {'Student_Name': 'Ms. Sana'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Karachi'}, {'Student_Name': 'Mr. Ali'}, {'Gender': 'Male'}, {'Age': '28'}, {'City': 'Islamabad'}, {'Student_Name': 'Mr. Ahmed'}, {'Gender': 'Male'}, {'Age': '26'}, {'City': 'Gujrat'}, {'Student_Name': 'Ms. Samra'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Gujranwala'}, {'Student_Name': 'Mr. Mustafa'}, {'Gender': 'Male'}, {'Age': '28'}, {'City': 'Multan'}], 'Learn How to Achieve Excellence in Love and Obedience of Hazrat Muhammad (PBUH)': [{'Student_Name': 'Ms. Fatima'}, {'Gender': 'Female'}, {'Age': '22'}, {'City': 'Lahore'}, {'Student_Name': 'Ms. Samra'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Karachi'}, {'Student_Name': 'Mr. Rizwan'}, {'Gender': 'Male'}, {'Age': '25'}, {'City': 'Lahore'}, {'Student_Name': 'Mr. Ahmed'}, {'Gender': 'Male'}, {'Age': '26'}, {'City': 'Karachi'}, {'Student_Name': 'Ms. Saman'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Lahore'}, {'Student_Name': 'Mr. Abdullah'}, {'Gender': 'Male'}, {'Age': '28'}, {'City': 'Lahore'}], 'Learn How to Become an Authority in Your Field': [{'Student_Name': 'Ms. Ayesha'}, {'Gender': 'Female'}, {'Age': '24'}, {'City': 'Lahore'}, {'Student_Name': 'Mr. Umer'}, {'Gender': 'Male'}, {'Age': '21'}, {'City': 'Lahore'}, {'Student_Name': 'Ms. Sana'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Islamabad'}, {'Student_Name': 'Mr. Ali'}, {'Gender': 'Male'}, {'Age': '28'}, {'City': 'Lahore'}, {'Student_Name': 'Ms. Sana'}, {'Gender': 'Female'}, {'Age': '23'}, {'City': 'Lahore'}, {'Student_Name': 'Mr. Ali'}, {'Gender': 'Male'}, {'Age': '28'}, {'City': 'Lahore'}, {'Student_Name': 'Mr. Ahmed'}, {'Gender': 'Male'}, {'Age': '26'}, {'City': 'Lahore'}]}

				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following Nested Dictionary and answer the questions given below

student_courses = {

‘FA15-BCS-01’: [

{‘Program’:’BS(CS)’}, {‘Degree’:’Bachelors in Computer Science’}

],

‘FA15-BCS-03’: [

{‘Program’:’BS(CE)’}, {‘Degree’:’Bachelors in Computer Science’}

],

‘FA15-BCS-05’: [

{‘Program’:’BS(CS)’}, {‘Degree’:’Bachelors in Computer Science’}

]}

  • Questions
    • Create a Dictionary within a List (as shown in this Chapter)?
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider a Nested Dictionary (similar to the one given in TODO Task 1) and answer the questions given below
  • Questions
    • Create a Dictionary within a List (as shown in this Chapter)?

Passing Nested Dictionary to a Function

  • Example 1 - Passing Nested Dictionary to a Function
				
					student_information = {
    1: {'Student_Name': 'Ms. Samavi','Gender': 'Female', 'Age': '24','City': 'Lahore'},
    2: {'Student_Name': 'Ms. Samra','Gender': 'Female', 'Age': '23','City': 'Karachi'},
    3: {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20',  'City': 'Multan'}
    }


def nested_dict_pairs_iterator(dict_obj):
    ''' This function accepts a nested dictionary as argument
        and iterate over all values of nested dictionaries
    '''
    # Iterate over all key-value pairs of dict argument
    for key, value in dict_obj.items():
         print(key,value)
             
try:
    nested_dict_pairs_iterator(student_information)
except Exception as ex:
    print(ex)

				
			
				
					1 {'Student_Name': 'Ms. Samavi', 'Gender': 'Female', 'Age': '24', 'City': 'Lahore'}
2 {'Student_Name': 'Ms. Samra', 'Gender': 'Female', 'Age': '23', 'City': 'Karachi'}
3 {'Student_Name': 'Mr. Imran', 'Gender': 'Male', 'Age': '20', 'City': 'Multan'}
				
			

TODO and Your Turn

Todo Tasks
Your Turn Tasks
Todo Tasks

TODO Task 1

  • Task
    • Consider the following Nested Dictionary and answer the questions given below

student_courses = {

‘FA15-BCS-01’:

{‘Program’:’BS(CS)’,’Degree’:’Bachelors in Computer Science’},

‘FA15-BCS-03’:

{‘Program’:’BS(CE)’,’Degree’:’Bachelors in Computer Science’},

‘FA15-BCS-05’:

{‘Program’:’BS(CS)’,’Degree’:’Bachelors in Computer Science’}}

  • Questions
    • Pass Nested Dictionary to a Function (as shown in this Chapter)?
Your Turn Tasks

Your Turn Task 1

  • Task
    • Consider a Nested Dictionary (similar to the one given in TODO Task 1) and answer the questions given below
  • Questions
    • Pass Nested Dictionary to a Function (as shown in this Chapter)?

Chapter Summary

  • Chapter Summary

In this Chapter, I presented the following main concepts:

  • Dictionary
    • Definition 1
    • In Python, Dictionary is a data structure which stores data as a set of unique identifiers, each of which have an associated value
    • This Data Pairing is called key-value pair
      • key
        • The unique identifier is called the key for an item of data
      • value
        • A value is either the data being identified or the location of that data
  • Definition 2
    • A Dictionary is a collection of key-value pairs
    • Note
      • In each key-value pair, the kay is mapped to its associated value.
  • Data Type – key
    • A Dictionary key can be almost any Python Object, but
      • Mostly Strings and Numbers are used keys
  • Data Type – value
    • A Dictionary value can be any arbitrary Python Object
      • Dictionary Declaration
  • A Dictionary can be declared using two methods
    • Method 1: Use {}
    • Method 2: Use dict() Function
  • Declaring an Empty Dictionary
    • Method 1: Use {}
    • Method 2: Use dict() Built in Function
  • Initializing a Dictionary
    • Method 1: Building a Complete Dictionary
    • Method 2: Building a Dictionary Incrementally
  • Access value of an Individual Dictionary Item
  • Accessing Elements of a Dictionary
    • Method 1 – Access Element(s) of a Dictionary using key Name inside []
    • Method 2 – Access Element(s) of a Dictionary using get() built-in Functions
  • Access List of keys in a Dictionary
    • Access List of keys in a Dictionary using key() built-in Function
  •  Accessing Elements of a Dictionary
    • Access List of keys in a Dictionary using key() built-in Function
  • Access List of values in a Dictionary
    • Access List of values in a Dictionary using values() built-in Function
  • Operations on Dictionary
    • Operation 1 – Creation
    • Operation 2 – Insertion
    • Operation 3 – Traversal
    • Operation 4 – Searching
    • Operation 5 – Sorting
    • Operation 6 – Merging
    • Operation 7 – Updation
    • Operation 8 – Deletion
  • Dictionary Comprehension
    • Dictionary comprehension is a simple method for (conditionally) transforming items of one dictionary into another dictionary without using loops
  • Nested Dictionary
    • A Nested Dictionary is a Dictionary of Dictionaries

In Next Chapter

  • In Next Chapter
  • In Sha Allah, in the next Chapter, I will present a detailed discussion on
  • Tuples in Python
Chapter 31 - List in Python
  • Previous
Chapter 33 - Tuples
  • Next
Share this article!
Facebook
Twitter
LinkedIn
About Us

Ilm O Irfan Technologies believes that honest dedicated hard work with the ethical approach of commitment true to every word, and trust-building is the road to success in any field of business or life.

Quick Links
  • About Us
  • Contact
Useful Links
  • Privacy Policy
  • Terms and Conditions
  • Disclaimer
  • Support
  • FAQ
Subscribe Our Newsletter
Facebook Twitter Linkedin Instagram Youtube

© 2022 Ilmo Irfan. All Rights Reserved.