SlideShare a Scribd company logo
1 of 34
NAVODAYA VIDYALAYA SAMITI
HYDERABAD REGION
E-CONTENT
COMPUTER SCIENCE CLASS XI
COMPUTATIONAL THINKING AND
PROGRAMMING-1
DICTIONARY IN PYTHON
SHIFA JAMES
PGT CS , JNV KADAPA
CONTENTS
▪ Definition, Creation, Accessing elements of a dictionary
▪ Add an item, modify an item in a dictionary; Traversal
▪ Functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del(),
del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count(),
sorted() , copy();
▪ Suggested programs :
▪ count the number of times a character appears in a given string using a dictionary,
▪ create a dictionary with names of employees, their salary and access them.
Learning Objectives
After completing this lesson, the students should be able to:
⮚ Understand the need of a Dictionary
⮚ Understand how to implement it in python.
⮚ Gain knowledge about Different types Operations in Dictionary
⮚ Understand about Different Methods and Built-in Functions in Dictionary
⮚ Implementing Dictionary in Program
INTRODUCTION
⮚Have you used a Telephone Directory ?
⮚How are the contents arranged in a Telephone
Directory ?
⮚Subscribers number gets stored according to his
name and address.
⮚Here name becomes a key and phone number
becomes a value.
⮚In dictionary, we have a concept of Key – Value
pair.
Dictionary - Definition
A Dictionary is an unordered collection of items where each item is a key-
value pair.
It is a mapping between a set of keys and a set of values. The key-value
pair is called an item.
Elements of a Dictionary are enclosed in curly brackets { } and are
separated by commas.
Dictionaries are mutable data types in the form of key:value , where key is
used to access the corresponding Value .
Keys are unique within a dictionary and are of immutable data types
whereas Values are of mutable types
Internally stored as Mappings
Internally, the key:value pair are associated with one another
with some internal function(called hash function). This way of
linking is called as mapping
Creating a Dictionary
• To create a dictionary, it is needed to collect
pairs of key:value in “{ }”.
•<dictionary-name> = { <key1>:<value1>, <key2>:<value2>, <key3>:<value3>. . . }
•Example:
Teachers = {“Rajeev”:”Math”, “Amal”:”Physics”, ”Arun”:”Chemistry“ , “ SJ”:”CS” }
In above given example :
Key-value pair Key Value
“Rajeev”:”Math” “Rajeev” “Math”
“Amal”:”Physics” “Amal” “Physics”
“Arun”:”Chemistry” “Arun” “Chemistry”
“SJ”:”CS” “SJ” “CS”
Different methods of creating a Dictionary
1) dict1 is an empty Dictionary created . Curly braces are used for empty
dictionary
Example :
>>> dict1 = {}
>>> dict1
{}
2) dict2 is an empty dictionary created using built-in function
>>> dict2 = dict()
>>> dict2
{}
Different methods of creating a Dictionary
3) dict3 is the dictionary that maps names of the students to respective marks in
percentage
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
Accessing keys and values simultaneously
▪ To access only keys of a dicionary , we can use the function keys()
▪ >>> mydict={'empno':1,'name':‘Arjun','dept':'sales','salary':20000}
▪ >>>mydict.keys()
▪ dict_keys(['empno', 'name', 'dept', 'salary'])
▪ To access only values of a dicionary , we can use the function values()
▪ >>>mydict.values()
▪ dict_values([1, ‘Arjun', 'sales', 20000])
▪ We can convert the sequence returned by keys() and values() by using list() as shown below:
▪ >>> list(mydict.keys())
▪ ['empno', 'name', 'dept', 'salary']
▪ >>> list(mydict.values()) [1, ‘Arjun', 'sales', 20000]
Characteristics of a Dictionary
▪ Unordered set
▪ A dictionary is a unordered set of key:value pair
▪ Not a sequence
▪ Unlike a string, tuple, and list, a dictionary is not a sequence because it is
unordered set of elements. The sequences are indexed by a range of ordinal
numbers. Hence they are ordered but a dictionary is an unordered collection
▪ Indexed by Keys, Not Numbers
▪ Dictionaries are indexed by keys. Keys are immutable type
Characteristics of a Dictionary
▪ Keys must be unique
▪ Each key within dictionary must be unique. However two unique keys can have same values.
For example
Data = {1:100, 2:200,3:300,4:200}
⮚Mutable
▪ Like lists, dictionary are also mutable. We can change the value of a certain “key” in place
▪ Data[3]=400
So, to change value of dictionary the format is :
DictionaryName[“key” / key ]=new_value
You can even add new key:value pair using the same format:
DictionaryName[“key” / key ]=new_value
Accessing Elements in a Dictionary
▪ The items of a dictionary are accessed via the keys rather than via their
relative positions or indices. Each key serves as the index and maps to a
value.
For example :
>>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict3['Ram']
89
>>> dict3['Sangeeta']
85
>>> dict3['Shyam'] #the key does not exist
KeyError: 'Shyam'
DICTIONARIES ARE MUTABLE
Add new item, Update an item , Delete an item
Adding elements to Dictionary
We can add a new item to the dictionary as shown in the following example:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1['Meena'] = 78
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78}
Note : The new item added will be at the end of the dictionary
Updating elements in Dictionary
▪ The existing dictionary can be modified by just overwriting the key-value pair. Example
to modify a given item in the dictionary:
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
#Marks of Suhel changed to 93.5
>>> dict1['Suhel'] = 93.5
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
Deleting elements from Dictionary
Method 1 - Using del command
▪ Syntax :
del dictionaryName[“Key”]
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> del dict1[‘Ram’]
>>> dict1
{'Mohan':95, 'Suhel':92, 'Sangeeta':85}
Note :
If you try to remove the item whose key does not exists, the python runtime error occurs.
Deleting elements from Dictionary
Method 2 - Using pop() function
Syntax :
dictionaryName.pop([“Key”])
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
>>> dict1.pop(‘Suhel’)
>>>dict1
{'Mohan':95,'Ram':89, 'Sangeeta':85}
Note:
if key passed to pop() doesn’t exists then python will raise an exception.
Traversing a Dictionary
We can access each item of the dictionary or traverse a dictionary using for loop.
Method 1
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
for key in dict1:
print(key , ':‘ , dict1[key])
Output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Traversing a Dictionary
▪ Method 2
▪ >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85}
for key,value in dict1.items():
print(key,':',value)
Output
Mohan: 95
Ram: 89
Suhel: 92
Sangeeta: 85
Dictionary Operations –
Membership operator – in
The membership operator in checks if the key is present in the
dictionary and returns True, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> 'Suhel' in dict1
True
Dictionary Operations –
Membership operator – not in
The not in operator returns True if the key is not present in the
dictionary, else it returns False.
>>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92,
'Sangeeta':85}
>>> 'Suhel' not in dict1
False
Dictionary Methods and Built-in Functions
Method Description Example
len() Returns the length or number of
key: value pairs of the dictionary
passed as the argument
>>> dict1 = {'Mohan':95,'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> len(dict1)
4
dict() Creates a dictionary from a
sequence of key-value pairs
pair1 = [('Mohan',95),('Ram',89),
('Suhel',92),('Sangeeta',85)]
>>> pair1
[('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]
>>> dict1 = dict(pair1)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
get() Returns the value
corresponding to the key
passed as the argument
If the key is not present in the
dictionary it will return None
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1.get('Sangeeta')
85
>>> dict1.get('Sohan')
>>>
Dictionary Methods and Built-in Functions
Method Description Example
keys() Returns a list of keys in
the dictionary
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1.keys()
dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta'])
values() Returns a list of values in
the dictionary
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1.values()
dict_values([95, 89, 92, 85])
items() Returns a list of tuples(key –
value) pair
>>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1.items()
dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92),
('Sangeeta', 85)])
clear() Deletes or clear all the items of
the dictionary
>>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85}
>>> dict1.clear()
>>> dict1
{ }
Dictionary Methods and Built-in Functions
Method Description Example
update() appends the key-value pair of the dictionary
passed as the argument to the key-value
pair of the given dictionary
>>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dict2 = {'Sohan':79,'Geeta':89}
>>> dict1.update(dict2)
>>> dict1
{'Mohan': 95, 'Ram': 89, 'Suhel': 92,
'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89}
>>> dict2
{'Sohan': 79, 'Geeta': 89}
popitem() It will remove the last dictionary item and
return key,value. of the removed item
>>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> k,v = dict1.popitem()
>>> print(k,”: “ v)
Sangeeta :85
copy() it will create a copy of dictionary. >>> dict1 = {'Mohan':95, 'Ram':89,
'Suhel':92, 'Sangeeta':85}
>>> dic2 = dict1.copy()
Dictionary Methods and Built-in Functions
Method Description Example
fromkeys() return new dictionary with
the given set of elements
as the keys of the
dictionary.
Note:
Set of elements should be
immutable type
>>>seq = ('name', 'age', 'sex')
>>>dict = dict.fromkeys(seq)
>>>print ("New Dictionary : “ , str(dict) )
New Dictionary : {'age': None, 'name': None, 'sex':
None}
>>>dict = dict.fromkeys(seq, 10)
>>>print ("New Dictionary : " , str(dict) )
New Dictionary : {'age': 10, 'name': 10, 'sex': 10}
setdefault() returns the value of the
item with the specified
key.
If the key does not exist,
insert the key, with the
specified value,
>>>car = { "brand": "Ford", “model": "Mustang",
"year": 1964 }
>>>x = car.setdefault("color", "white“)
>>>print(x)
white
Dictionary Methods and Built-in Functions
Method Description Example
sorted() this function is used to sort the key or
value of dictionary in either ascending or
descending order. By default it will sort
the keys.
To display in descending order
>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}
>>> print(sorted(Dict1))
{1: 111, 2: 222, 3: 300, 4: 444, 5: 555}
>>>print(sorted(Dict1, reverse = ‘True’))
{5:555,4:444, 3:333 , 2:222 , 1:111}
min() This function returns lowest value in
dictionary, this will work only if all the
values in dictionary is of numeric type
>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}
>>>print(min(Dict1.values()))
111
max() This function returns highest value in
dictionary, this will work only if all the
values in dictionary is of numeric type
>>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222}
>>>print(max(Dict1.values()))
555
SUGGESTED PROGRAMS
Program 1
#Count the number of times a character appears in a given string
st = input("Enter a string: ")
dic = {} #creates an empty dictionary
for ch in st:
if ch in dic: #if next character is already in the dictionary
dic[ch] += 1
else:
dic[ch] = 1 #if ch appears for the first time
for key in dic:
print(key,':',dic[key])
Output:
Enter a string: HelloWorld
H : 1
e : 1
l : 3
o : 2
W : 1
r : 1
d : 1
Program 2
#Program to create a dictionary which stores names of the employee
and their salary
num = int(input("Enter the number of employees whose data to be stored: "))
count = 1
employee = dict() #create an empty dictionary
while count <= num:
name = input("Enter the name of the Employee: ")
salary = int(input("Enter the salary: "))
employee[name] = salary
count += 1
print (‘nDetails of Employees ‘)
print("nnEMPLOYEE_NAMEtSALARYn~~~~~~~~~~~~~~~~~")
for k in employee:
print(k,'tt',employee[k])
Output
Enter the number of employees to be stored: 5
Enter the name of the Employee: 'Tarun'
Enter the salary: 12000
Enter the name of the Employee: 'Amina'
Enter the salary: 34000
Enter the name of the Employee: 'Joseph'
Enter the salary: 24000
Enter the name of the Employee: 'Rahul'
Enter the salary: 30000
Enter the name of the Employee: 'Zoya‘
Enter the salary: 25000
Summary
❖Dictionary is a mapping (non-scalar) data type.
❖It is an unordered collection of key-value pair; keyvalue pair are put inside curly braces.
❖Each key is separated from its value by a colon.
❖Keys are unique and act as the index.
❖Keys are of immutable type but values can be mutable.
❖We can add an item, modify an item in a dictionary;
❖Functions/methods used in Dictionary are – len(), dict(), keys(), values(), items(), get(), update(),
del(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted().
BIBLIOGRAPHY:
1. Computer Science Textbook for class XI
by NCERT
2. Computer Science with Python
by Sumita Arora
3. Computer Science with Python
by Preeti Arora

More Related Content

What's hot (20)

Advanced Sql Training
Advanced Sql TrainingAdvanced Sql Training
Advanced Sql Training
 
Python Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG ManiaplPython Workshop Part 2. LUG Maniapl
Python Workshop Part 2. LUG Maniapl
 
Triggers in SQL | Edureka
Triggers in SQL | EdurekaTriggers in SQL | Edureka
Triggers in SQL | Edureka
 
Ms excel 2007
Ms excel 2007Ms excel 2007
Ms excel 2007
 
sql function(ppt)
sql function(ppt)sql function(ppt)
sql function(ppt)
 
SQL Functions
SQL FunctionsSQL Functions
SQL Functions
 
Taller arreglos en pseint
Taller arreglos en pseintTaller arreglos en pseint
Taller arreglos en pseint
 
Rahat &amp; juhith
Rahat &amp; juhithRahat &amp; juhith
Rahat &amp; juhith
 
Aggregate functions
Aggregate functionsAggregate functions
Aggregate functions
 
DBMS 10 | Database Transactions
DBMS 10 | Database TransactionsDBMS 10 | Database Transactions
DBMS 10 | Database Transactions
 
Sql interview questions and answers
Sql interview questions and  answersSql interview questions and  answers
Sql interview questions and answers
 
View & index in SQL
View & index in SQLView & index in SQL
View & index in SQL
 
What is in reality a DAX filter context
What is in reality a DAX filter contextWhat is in reality a DAX filter context
What is in reality a DAX filter context
 
Crystal report
Crystal reportCrystal report
Crystal report
 
Arrays
ArraysArrays
Arrays
 
Nested Queries-SQL.ppt
Nested Queries-SQL.pptNested Queries-SQL.ppt
Nested Queries-SQL.ppt
 
Dml and ddl
Dml and ddlDml and ddl
Dml and ddl
 
DPLYR package in R
DPLYR package in RDPLYR package in R
DPLYR package in R
 
Database Programming using SQL
Database Programming using SQLDatabase Programming using SQL
Database Programming using SQL
 
oracle Sql constraint
oracle  Sql constraint oracle  Sql constraint
oracle Sql constraint
 

Similar to Ch 7 Dictionaries 1.pptx

An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Pythonyashar Aliabasi
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptxKalashJain27
 
ch 13 Dictionaries2.pptx
ch 13 Dictionaries2.pptxch 13 Dictionaries2.pptx
ch 13 Dictionaries2.pptxsogarongt
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxNishanSidhu2
 
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers..."Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...ZainabHaneen
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonMSB Academy
 
316_16SCCCS4_2020052505222431.pptdatabasex
316_16SCCCS4_2020052505222431.pptdatabasex316_16SCCCS4_2020052505222431.pptdatabasex
316_16SCCCS4_2020052505222431.pptdatabasexabhaysonone0
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl courseMarc Logghe
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonRaajendra M
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in pythonhydpy
 
Dictionary part 1
Dictionary part 1Dictionary part 1
Dictionary part 1RishuKaul2
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfMeha46
 

Similar to Ch 7 Dictionaries 1.pptx (20)

An Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in PythonAn Introduction to Tuple List Dictionary in Python
An Introduction to Tuple List Dictionary in Python
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
 
Dictionaries and Sets
Dictionaries and SetsDictionaries and Sets
Dictionaries and Sets
 
ch 13 Dictionaries2.pptx
ch 13 Dictionaries2.pptxch 13 Dictionaries2.pptx
ch 13 Dictionaries2.pptx
 
UNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptxUNIT 1 - Revision of Basics - II.pptx
UNIT 1 - Revision of Basics - II.pptx
 
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers..."Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
316_16SCCCS4_2020052505222431.pptdatabasex
316_16SCCCS4_2020052505222431.pptdatabasex316_16SCCCS4_2020052505222431.pptdatabasex
316_16SCCCS4_2020052505222431.pptdatabasex
 
Dictionary.pptx
Dictionary.pptxDictionary.pptx
Dictionary.pptx
 
Marc’s (bio)perl course
Marc’s (bio)perl courseMarc’s (bio)perl course
Marc’s (bio)perl course
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Ch_13_Dictionary.pptx
Ch_13_Dictionary.pptxCh_13_Dictionary.pptx
Ch_13_Dictionary.pptx
 
Array andfunction
Array andfunctionArray andfunction
Array andfunction
 
SQL.ppt
SQL.pptSQL.ppt
SQL.ppt
 
Datastructures in python
Datastructures in pythonDatastructures in python
Datastructures in python
 
Dictionary part 1
Dictionary part 1Dictionary part 1
Dictionary part 1
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllfPython-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
 
Dictionary
DictionaryDictionary
Dictionary
 
Dictionaries.pptx
Dictionaries.pptxDictionaries.pptx
Dictionaries.pptx
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Ch 7 Dictionaries 1.pptx

  • 1. NAVODAYA VIDYALAYA SAMITI HYDERABAD REGION E-CONTENT COMPUTER SCIENCE CLASS XI
  • 2. COMPUTATIONAL THINKING AND PROGRAMMING-1 DICTIONARY IN PYTHON SHIFA JAMES PGT CS , JNV KADAPA
  • 3. CONTENTS ▪ Definition, Creation, Accessing elements of a dictionary ▪ Add an item, modify an item in a dictionary; Traversal ▪ Functions/methods – len(), dict(), keys(), values(), items(), get(), update(), del(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), count(), sorted() , copy(); ▪ Suggested programs : ▪ count the number of times a character appears in a given string using a dictionary, ▪ create a dictionary with names of employees, their salary and access them.
  • 4. Learning Objectives After completing this lesson, the students should be able to: ⮚ Understand the need of a Dictionary ⮚ Understand how to implement it in python. ⮚ Gain knowledge about Different types Operations in Dictionary ⮚ Understand about Different Methods and Built-in Functions in Dictionary ⮚ Implementing Dictionary in Program
  • 5. INTRODUCTION ⮚Have you used a Telephone Directory ? ⮚How are the contents arranged in a Telephone Directory ? ⮚Subscribers number gets stored according to his name and address. ⮚Here name becomes a key and phone number becomes a value. ⮚In dictionary, we have a concept of Key – Value pair.
  • 6. Dictionary - Definition A Dictionary is an unordered collection of items where each item is a key- value pair. It is a mapping between a set of keys and a set of values. The key-value pair is called an item. Elements of a Dictionary are enclosed in curly brackets { } and are separated by commas. Dictionaries are mutable data types in the form of key:value , where key is used to access the corresponding Value . Keys are unique within a dictionary and are of immutable data types whereas Values are of mutable types
  • 7. Internally stored as Mappings Internally, the key:value pair are associated with one another with some internal function(called hash function). This way of linking is called as mapping
  • 8. Creating a Dictionary • To create a dictionary, it is needed to collect pairs of key:value in “{ }”. •<dictionary-name> = { <key1>:<value1>, <key2>:<value2>, <key3>:<value3>. . . } •Example: Teachers = {“Rajeev”:”Math”, “Amal”:”Physics”, ”Arun”:”Chemistry“ , “ SJ”:”CS” } In above given example : Key-value pair Key Value “Rajeev”:”Math” “Rajeev” “Math” “Amal”:”Physics” “Amal” “Physics” “Arun”:”Chemistry” “Arun” “Chemistry” “SJ”:”CS” “SJ” “CS”
  • 9. Different methods of creating a Dictionary 1) dict1 is an empty Dictionary created . Curly braces are used for empty dictionary Example : >>> dict1 = {} >>> dict1 {} 2) dict2 is an empty dictionary created using built-in function >>> dict2 = dict() >>> dict2 {}
  • 10. Different methods of creating a Dictionary 3) dict3 is the dictionary that maps names of the students to respective marks in percentage >>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> dict3 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85}
  • 11. Accessing keys and values simultaneously ▪ To access only keys of a dicionary , we can use the function keys() ▪ >>> mydict={'empno':1,'name':‘Arjun','dept':'sales','salary':20000} ▪ >>>mydict.keys() ▪ dict_keys(['empno', 'name', 'dept', 'salary']) ▪ To access only values of a dicionary , we can use the function values() ▪ >>>mydict.values() ▪ dict_values([1, ‘Arjun', 'sales', 20000]) ▪ We can convert the sequence returned by keys() and values() by using list() as shown below: ▪ >>> list(mydict.keys()) ▪ ['empno', 'name', 'dept', 'salary'] ▪ >>> list(mydict.values()) [1, ‘Arjun', 'sales', 20000]
  • 12. Characteristics of a Dictionary ▪ Unordered set ▪ A dictionary is a unordered set of key:value pair ▪ Not a sequence ▪ Unlike a string, tuple, and list, a dictionary is not a sequence because it is unordered set of elements. The sequences are indexed by a range of ordinal numbers. Hence they are ordered but a dictionary is an unordered collection ▪ Indexed by Keys, Not Numbers ▪ Dictionaries are indexed by keys. Keys are immutable type
  • 13. Characteristics of a Dictionary ▪ Keys must be unique ▪ Each key within dictionary must be unique. However two unique keys can have same values. For example Data = {1:100, 2:200,3:300,4:200} ⮚Mutable ▪ Like lists, dictionary are also mutable. We can change the value of a certain “key” in place ▪ Data[3]=400 So, to change value of dictionary the format is : DictionaryName[“key” / key ]=new_value You can even add new key:value pair using the same format: DictionaryName[“key” / key ]=new_value
  • 14. Accessing Elements in a Dictionary ▪ The items of a dictionary are accessed via the keys rather than via their relative positions or indices. Each key serves as the index and maps to a value. For example : >>> dict3 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> dict3['Ram'] 89 >>> dict3['Sangeeta'] 85 >>> dict3['Shyam'] #the key does not exist KeyError: 'Shyam'
  • 15. DICTIONARIES ARE MUTABLE Add new item, Update an item , Delete an item
  • 16. Adding elements to Dictionary We can add a new item to the dictionary as shown in the following example: >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> dict1['Meena'] = 78 >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Meena': 78} Note : The new item added will be at the end of the dictionary
  • 17. Updating elements in Dictionary ▪ The existing dictionary can be modified by just overwriting the key-value pair. Example to modify a given item in the dictionary: >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} #Marks of Suhel changed to 93.5 >>> dict1['Suhel'] = 93.5 >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 93.5, 'Sangeeta': 85}
  • 18. Deleting elements from Dictionary Method 1 - Using del command ▪ Syntax : del dictionaryName[“Key”] >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> del dict1[‘Ram’] >>> dict1 {'Mohan':95, 'Suhel':92, 'Sangeeta':85} Note : If you try to remove the item whose key does not exists, the python runtime error occurs.
  • 19. Deleting elements from Dictionary Method 2 - Using pop() function Syntax : dictionaryName.pop([“Key”]) >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> dict1.pop(‘Suhel’) >>>dict1 {'Mohan':95,'Ram':89, 'Sangeeta':85} Note: if key passed to pop() doesn’t exists then python will raise an exception.
  • 20. Traversing a Dictionary We can access each item of the dictionary or traverse a dictionary using for loop. Method 1 >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} for key in dict1: print(key , ':‘ , dict1[key]) Output Mohan: 95 Ram: 89 Suhel: 92 Sangeeta: 85
  • 21. Traversing a Dictionary ▪ Method 2 ▪ >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} for key,value in dict1.items(): print(key,':',value) Output Mohan: 95 Ram: 89 Suhel: 92 Sangeeta: 85
  • 22. Dictionary Operations – Membership operator – in The membership operator in checks if the key is present in the dictionary and returns True, else it returns False. >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> 'Suhel' in dict1 True
  • 23. Dictionary Operations – Membership operator – not in The not in operator returns True if the key is not present in the dictionary, else it returns False. >>> dict1 = {'Mohan':95,'Ram':89,'Suhel':92, 'Sangeeta':85} >>> 'Suhel' not in dict1 False
  • 24. Dictionary Methods and Built-in Functions Method Description Example len() Returns the length or number of key: value pairs of the dictionary passed as the argument >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> len(dict1) 4 dict() Creates a dictionary from a sequence of key-value pairs pair1 = [('Mohan',95),('Ram',89), ('Suhel',92),('Sangeeta',85)] >>> pair1 [('Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)] >>> dict1 = dict(pair1) >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85} get() Returns the value corresponding to the key passed as the argument If the key is not present in the dictionary it will return None >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.get('Sangeeta') 85 >>> dict1.get('Sohan') >>>
  • 25. Dictionary Methods and Built-in Functions Method Description Example keys() Returns a list of keys in the dictionary >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.keys() dict_keys(['Mohan', 'Ram', 'Suhel', 'Sangeeta']) values() Returns a list of values in the dictionary >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.values() dict_values([95, 89, 92, 85]) items() Returns a list of tuples(key – value) pair >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.items() dict_items([( 'Mohan', 95), ('Ram', 89), ('Suhel', 92), ('Sangeeta', 85)]) clear() Deletes or clear all the items of the dictionary >>> dict1 = {'Mohan':95,'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict1.clear() >>> dict1 { }
  • 26. Dictionary Methods and Built-in Functions Method Description Example update() appends the key-value pair of the dictionary passed as the argument to the key-value pair of the given dictionary >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dict2 = {'Sohan':79,'Geeta':89} >>> dict1.update(dict2) >>> dict1 {'Mohan': 95, 'Ram': 89, 'Suhel': 92, 'Sangeeta': 85, 'Sohan': 79, 'Geeta': 89} >>> dict2 {'Sohan': 79, 'Geeta': 89} popitem() It will remove the last dictionary item and return key,value. of the removed item >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> k,v = dict1.popitem() >>> print(k,”: “ v) Sangeeta :85 copy() it will create a copy of dictionary. >>> dict1 = {'Mohan':95, 'Ram':89, 'Suhel':92, 'Sangeeta':85} >>> dic2 = dict1.copy()
  • 27. Dictionary Methods and Built-in Functions Method Description Example fromkeys() return new dictionary with the given set of elements as the keys of the dictionary. Note: Set of elements should be immutable type >>>seq = ('name', 'age', 'sex') >>>dict = dict.fromkeys(seq) >>>print ("New Dictionary : “ , str(dict) ) New Dictionary : {'age': None, 'name': None, 'sex': None} >>>dict = dict.fromkeys(seq, 10) >>>print ("New Dictionary : " , str(dict) ) New Dictionary : {'age': 10, 'name': 10, 'sex': 10} setdefault() returns the value of the item with the specified key. If the key does not exist, insert the key, with the specified value, >>>car = { "brand": "Ford", “model": "Mustang", "year": 1964 } >>>x = car.setdefault("color", "white“) >>>print(x) white
  • 28. Dictionary Methods and Built-in Functions Method Description Example sorted() this function is used to sort the key or value of dictionary in either ascending or descending order. By default it will sort the keys. To display in descending order >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>> print(sorted(Dict1)) {1: 111, 2: 222, 3: 300, 4: 444, 5: 555} >>>print(sorted(Dict1, reverse = ‘True’)) {5:555,4:444, 3:333 , 2:222 , 1:111} min() This function returns lowest value in dictionary, this will work only if all the values in dictionary is of numeric type >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>>print(min(Dict1.values())) 111 max() This function returns highest value in dictionary, this will work only if all the values in dictionary is of numeric type >>> Dict1 = {1: 111, 4: 444 , 3: 300, 5: 555 , 2: 222} >>>print(max(Dict1.values())) 555
  • 30. Program 1 #Count the number of times a character appears in a given string st = input("Enter a string: ") dic = {} #creates an empty dictionary for ch in st: if ch in dic: #if next character is already in the dictionary dic[ch] += 1 else: dic[ch] = 1 #if ch appears for the first time for key in dic: print(key,':',dic[key]) Output: Enter a string: HelloWorld H : 1 e : 1 l : 3 o : 2 W : 1 r : 1 d : 1
  • 31. Program 2 #Program to create a dictionary which stores names of the employee and their salary num = int(input("Enter the number of employees whose data to be stored: ")) count = 1 employee = dict() #create an empty dictionary while count <= num: name = input("Enter the name of the Employee: ") salary = int(input("Enter the salary: ")) employee[name] = salary count += 1 print (‘nDetails of Employees ‘) print("nnEMPLOYEE_NAMEtSALARYn~~~~~~~~~~~~~~~~~") for k in employee: print(k,'tt',employee[k])
  • 32. Output Enter the number of employees to be stored: 5 Enter the name of the Employee: 'Tarun' Enter the salary: 12000 Enter the name of the Employee: 'Amina' Enter the salary: 34000 Enter the name of the Employee: 'Joseph' Enter the salary: 24000 Enter the name of the Employee: 'Rahul' Enter the salary: 30000 Enter the name of the Employee: 'Zoya‘ Enter the salary: 25000
  • 33. Summary ❖Dictionary is a mapping (non-scalar) data type. ❖It is an unordered collection of key-value pair; keyvalue pair are put inside curly braces. ❖Each key is separated from its value by a colon. ❖Keys are unique and act as the index. ❖Keys are of immutable type but values can be mutable. ❖We can add an item, modify an item in a dictionary; ❖Functions/methods used in Dictionary are – len(), dict(), keys(), values(), items(), get(), update(), del(), del, clear(), fromkeys(), copy(), pop(), popitem(), setdefault(), max(), min(), sorted().
  • 34. BIBLIOGRAPHY: 1. Computer Science Textbook for class XI by NCERT 2. Computer Science with Python by Sumita Arora 3. Computer Science with Python by Preeti Arora