SlideShare a Scribd company logo
1 of 14
DICTIONARY
• WHAT IS DICTIONARY?
• HOW TO CREATE DICTIONARY?
• HOW TO ACCESS / TRAVERSE ELEMENTS IN DICTIONARY?
• DICTIONARY OPERATIONS
• DICTIONARY FUNCTIONS
WHAT IS DICTIONARY?
• It is unordered collection of elements in the form key:value pair.
• Keys must be of immutable type such as string,number or a
tuple.
• Values can be of any type.
• It is Mutable.
• Indexed by keys not by Numbers.
• Keys must be unique.
• Dictionaries are also called ‘associative arrays’ or ‘mappings’ or
hashes.
• Examples:
• D1 = { }
• Signal = {‘Red’:1, ‘Green’:2, ‘Yellow’:3}
• Dict1={1:’test’, ‘string’: 2, ‘list’:[1,2,3], (5,7):’tuple’}
How to create Dictionary?
1) Initialisation
Signal = {‘Red’:1, ‘Green’:2, ‘Yellow’:3}
2) Using dict( )
1) D = dict( )  Creates Empty dictionary
2) Signal = dict(Red=1,Green=2, Yellow=3)
3) Signal = dict([‘Red’,1],[‘Green’,2],[‘Yellow’,3])
4) Signal = dict(zip((‘Red’,’Green’,’Yellow’),(1,2,3)))
HOW TO ACCESS ELEMENTS IN A DICTIONARY?
• In Dictionary, the elements are accessed through keys.
Syntax: <DictionaryName>[<key>]
Months={‘Jan’:31,’Feb’:28,’Mar’:31,’Apr’:30,’May’:31}
Vowels={1:’a’, 2:’e’, 3:’i’, 4:’o’, 5:’u’}
>>>Months[‘Feb’]
28
>>>Months[‘May’]
31
>>>Vowels[3]
I
>>>Vowels[‘e’]
Error Message
Traversing a Dictionary
Syntax:
for <item> in <Dictionary> :
item Keys in dictionary
Dictionary[item]  Value corresponding to key
Ex:1
D1={‘Red’:1, ‘Green’:2, ‘Yellow’:3}
for key in D1:
print(key, D1[key])
Output:
Red 1
Green 2
Yellow 3
for i in D1:
print(D1[i])
Output: Output:
1 2
2 1
3 3
Dictionaries are unordered set of
elements, the printed order of elements
is not same as the order you store the
elements in.
CHARACTERISTICS OF A DICTIONARY
1. Unordered Set
2. Not a sequence
3. Indexed by keys not by Numbers
4. Keys must be unique
5. Mutable
6. Internally stored as Mappings
Dictionary Operations
Student={‘Name’:’John’, ‘Age’:16}
1) Adding Elements to Dictionary
Syntax: Dictionary[key] = value
>>> Student[‘Class’]=12
>>> Student
{‘Name’:’John’, ‘Age’:16,’Class’:12}
2) Updating Existing elements
Syntax: Dictionary[key]=Newvalue
Ex: Student[‘Age’]=17
Result: Student={‘Name’:’John’, ‘Age’:17}
Student[‘age’]=18
Result: : Student={‘Name’:’John’, ‘Age’:17, ‘age’:18}
3) Deleting Elements from Dictionay
i) Using del statement
Syntax: del dictionary[key]
>>>del Student[‘age’]
>>>del Student
>>>del Student[‘DOB’]
Error Message : KeyError: 'DOB‘
ii) Using pop( ) method
Syntax: <Dictionary>.pop(<key>)
>>>Student.pop(‘Age’)
16
4) Checking for Existence of a Key
Use membership operator in and not in
<key> in <Dictionary)
Returns True if the given key is present
<key> not in <Dictionary>
 Returns True if the given key is not present
Ex:
>>>’Age’ in Student
True
>>>’DOB’ not in Student
True
Dictionary Functions and Methods
Student = {‘Name’:’John’, ‘Age’:16, ‘Class’:12}
1) len( )  Returns no of elements in a dictionary
Syntax: len(<dictionary>)
Argument: 1 argument of type Dictionary
Return: Integer
Example: >>> len(Student)
3
2) clear( )  Clears/Deletes all elements in a dictionary
Syntax: <dictionary>.clear( )
Argument: No argument
Return: Nothing
Example: >>>Student.clear( )
>>> Student
{ }
3) get( )  Get the item with given key or User defined message
Syntax: <dictionry>.get(key , [default])
Argument: 1 – Essential argument, 1 – Optional argument
Return: Object/ Value
Example: >>> Student.get(‘Name’)
John
>>>Student.Get(‘dob’, “Key does not exist”)
Key does not exist
4) items( )  Returns all the items in the dictionary as (key,value) tuple
Syntax: <dictionary>.items( )
Argument: No argument
Return: Sequence of (key, value) pair
Example: >>>Student.items( )
dict_items([('Name', 'John'), ('Age', 17), ('Class', 12)])
5) keys( )  Returns all the keys in dictionary as a list.
Syntax: <dictionary>.keys( )
Argument: No argument
Return: List of keys
Example: >>> Student.keys( )
[‘Name’, ‘Age’, ‘Class’]
6) values( )  Returns all the values in dictionary as a list.
Syntax: <dictionary>.values( )
Argument: No argument
Return: List of values
Example: >>> Student.values( )
[‘John’, 16,12]
7) update( )  Merges key:value pair from new dictionary into the original
dictionary, adding or replacing as needed.
Syntax: <dictionary>.update(<dictionary>)
Argument: 1 argument of type dictionary
Return: Nothing
Example:>>> School ={‘name’:’vvs’, ‘board’:cbse}
>>>Student.update(School)
>>>Student
{‘Name’:’John’, ‘Age’:16,’Class’:12, ‘name’:’vvs’, ‘board’:cbse }
8) pop( )  Returns and deletes element from dictionary
Syntax: <dictionary>.pop(<key>)
Argument: 1 argument of key item
Return: Value of any type
Example: >>>Student. pop(‘Class’)
12
>>>Student
{‘Name’: ’John’, ‘Age’:16}
THANK YOU 

More Related Content

What's hot

Functions in c language
Functions in c language Functions in c language
Functions in c language tanmaymodi4
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, RecursionSreedhar Chowdam
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentationVedaGayathri1
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocationViji B
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationRabin BK
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and typesimtiazalijoono
 
Python dictionary
Python dictionaryPython dictionary
Python dictionarySagar Kumar
 
C programming - String
C programming - StringC programming - String
C programming - StringAchyut Devkota
 
Strings in c
Strings in cStrings in c
Strings in cvampugani
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queueRajkiran Nadar
 
String In C Language
String In C Language String In C Language
String In C Language Simplilearn
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in PythonRaajendra M
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CSowmya Jyothi
 

What's hot (20)

The string class
The string classThe string class
The string class
 
C string
C stringC string
C string
 
Python recursion
Python recursionPython recursion
Python recursion
 
Functions in c language
Functions in c language Functions in c language
Functions in c language
 
Chapter 17 Tuples
Chapter 17 TuplesChapter 17 Tuples
Chapter 17 Tuples
 
File in C language
File in C languageFile in C language
File in C language
 
C Programming Storage classes, Recursion
C Programming Storage classes, RecursionC Programming Storage classes, Recursion
C Programming Storage classes, Recursion
 
C++ oop
C++ oopC++ oop
C++ oop
 
Python strings presentation
Python strings presentationPython strings presentation
Python strings presentation
 
8 python data structure-1
8 python data structure-18 python data structure-1
8 python data structure-1
 
Dynamic memory allocation
Dynamic memory allocationDynamic memory allocation
Dynamic memory allocation
 
Pointers and Dynamic Memory Allocation
Pointers and Dynamic Memory AllocationPointers and Dynamic Memory Allocation
Pointers and Dynamic Memory Allocation
 
Programming Fundamentals Functions in C and types
Programming Fundamentals  Functions in C  and typesProgramming Fundamentals  Functions in C  and types
Programming Fundamentals Functions in C and types
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
C programming - String
C programming - StringC programming - String
C programming - String
 
Strings in c
Strings in cStrings in c
Strings in c
 
Data structure , stack , queue
Data structure , stack , queueData structure , stack , queue
Data structure , stack , queue
 
String In C Language
String In C Language String In C Language
String In C Language
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
 
Unit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in CUnit ii chapter 2 Decision making and Branching in C
Unit ii chapter 2 Decision making and Branching in C
 

Similar to Ch_13_Dictionary.pptx

Similar to Ch_13_Dictionary.pptx (20)

Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
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
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
 
.net F# mutable dictionay
.net F# mutable dictionay.net F# mutable dictionay
.net F# mutable dictionay
 
Dictionary.pptx
Dictionary.pptxDictionary.pptx
Dictionary.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 Python
 
Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1Programming in python Unit-1 Part-1
Programming in python Unit-1 Part-1
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
 
2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt2 UNIT CH3 Dictionaries v1.ppt
2 UNIT CH3 Dictionaries v1.ppt
 
Dictionaries.pptx
Dictionaries.pptxDictionaries.pptx
Dictionaries.pptx
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
ppt_pspp.pdf
ppt_pspp.pdfppt_pspp.pdf
ppt_pspp.pdf
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
14 Skip Lists
14 Skip Lists14 Skip Lists
14 Skip Lists
 
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptxLecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
Lecture-15-Tuples-and-Dictionaries-Oct23-2018.pptx
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
02python.ppt
02python.ppt02python.ppt
02python.ppt
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
 
dictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptxdictionary14 ppt FINAL.pptx
dictionary14 ppt FINAL.pptx
 

Recently uploaded

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersChitralekhaTherkar
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfUmakantAnnand
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docxPoojaSen20
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 

Recently uploaded (20)

Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
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
 
Micromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of PowdersMicromeritics - Fundamental and Derived Properties of Powders
Micromeritics - Fundamental and Derived Properties of Powders
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
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
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Concept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.CompdfConcept of Vouching. B.Com(Hons) /B.Compdf
Concept of Vouching. B.Com(Hons) /B.Compdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
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
 
MENTAL STATUS EXAMINATION format.docx
MENTAL     STATUS EXAMINATION format.docxMENTAL     STATUS EXAMINATION format.docx
MENTAL STATUS EXAMINATION format.docx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
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
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 

Ch_13_Dictionary.pptx

  • 1. DICTIONARY • WHAT IS DICTIONARY? • HOW TO CREATE DICTIONARY? • HOW TO ACCESS / TRAVERSE ELEMENTS IN DICTIONARY? • DICTIONARY OPERATIONS • DICTIONARY FUNCTIONS
  • 2. WHAT IS DICTIONARY? • It is unordered collection of elements in the form key:value pair. • Keys must be of immutable type such as string,number or a tuple. • Values can be of any type. • It is Mutable. • Indexed by keys not by Numbers. • Keys must be unique. • Dictionaries are also called ‘associative arrays’ or ‘mappings’ or hashes. • Examples: • D1 = { } • Signal = {‘Red’:1, ‘Green’:2, ‘Yellow’:3} • Dict1={1:’test’, ‘string’: 2, ‘list’:[1,2,3], (5,7):’tuple’}
  • 3. How to create Dictionary? 1) Initialisation Signal = {‘Red’:1, ‘Green’:2, ‘Yellow’:3} 2) Using dict( ) 1) D = dict( )  Creates Empty dictionary 2) Signal = dict(Red=1,Green=2, Yellow=3) 3) Signal = dict([‘Red’,1],[‘Green’,2],[‘Yellow’,3]) 4) Signal = dict(zip((‘Red’,’Green’,’Yellow’),(1,2,3)))
  • 4. HOW TO ACCESS ELEMENTS IN A DICTIONARY? • In Dictionary, the elements are accessed through keys. Syntax: <DictionaryName>[<key>] Months={‘Jan’:31,’Feb’:28,’Mar’:31,’Apr’:30,’May’:31} Vowels={1:’a’, 2:’e’, 3:’i’, 4:’o’, 5:’u’} >>>Months[‘Feb’] 28 >>>Months[‘May’] 31 >>>Vowels[3] I >>>Vowels[‘e’] Error Message
  • 5. Traversing a Dictionary Syntax: for <item> in <Dictionary> : item Keys in dictionary Dictionary[item]  Value corresponding to key Ex:1 D1={‘Red’:1, ‘Green’:2, ‘Yellow’:3} for key in D1: print(key, D1[key]) Output: Red 1 Green 2 Yellow 3 for i in D1: print(D1[i]) Output: Output: 1 2 2 1 3 3 Dictionaries are unordered set of elements, the printed order of elements is not same as the order you store the elements in.
  • 6. CHARACTERISTICS OF A DICTIONARY 1. Unordered Set 2. Not a sequence 3. Indexed by keys not by Numbers 4. Keys must be unique 5. Mutable 6. Internally stored as Mappings
  • 7. Dictionary Operations Student={‘Name’:’John’, ‘Age’:16} 1) Adding Elements to Dictionary Syntax: Dictionary[key] = value >>> Student[‘Class’]=12 >>> Student {‘Name’:’John’, ‘Age’:16,’Class’:12} 2) Updating Existing elements Syntax: Dictionary[key]=Newvalue Ex: Student[‘Age’]=17 Result: Student={‘Name’:’John’, ‘Age’:17} Student[‘age’]=18 Result: : Student={‘Name’:’John’, ‘Age’:17, ‘age’:18}
  • 8. 3) Deleting Elements from Dictionay i) Using del statement Syntax: del dictionary[key] >>>del Student[‘age’] >>>del Student >>>del Student[‘DOB’] Error Message : KeyError: 'DOB‘ ii) Using pop( ) method Syntax: <Dictionary>.pop(<key>) >>>Student.pop(‘Age’) 16
  • 9. 4) Checking for Existence of a Key Use membership operator in and not in <key> in <Dictionary) Returns True if the given key is present <key> not in <Dictionary>  Returns True if the given key is not present Ex: >>>’Age’ in Student True >>>’DOB’ not in Student True
  • 10. Dictionary Functions and Methods Student = {‘Name’:’John’, ‘Age’:16, ‘Class’:12} 1) len( )  Returns no of elements in a dictionary Syntax: len(<dictionary>) Argument: 1 argument of type Dictionary Return: Integer Example: >>> len(Student) 3 2) clear( )  Clears/Deletes all elements in a dictionary Syntax: <dictionary>.clear( ) Argument: No argument Return: Nothing Example: >>>Student.clear( ) >>> Student { }
  • 11. 3) get( )  Get the item with given key or User defined message Syntax: <dictionry>.get(key , [default]) Argument: 1 – Essential argument, 1 – Optional argument Return: Object/ Value Example: >>> Student.get(‘Name’) John >>>Student.Get(‘dob’, “Key does not exist”) Key does not exist 4) items( )  Returns all the items in the dictionary as (key,value) tuple Syntax: <dictionary>.items( ) Argument: No argument Return: Sequence of (key, value) pair Example: >>>Student.items( ) dict_items([('Name', 'John'), ('Age', 17), ('Class', 12)])
  • 12. 5) keys( )  Returns all the keys in dictionary as a list. Syntax: <dictionary>.keys( ) Argument: No argument Return: List of keys Example: >>> Student.keys( ) [‘Name’, ‘Age’, ‘Class’] 6) values( )  Returns all the values in dictionary as a list. Syntax: <dictionary>.values( ) Argument: No argument Return: List of values Example: >>> Student.values( ) [‘John’, 16,12]
  • 13. 7) update( )  Merges key:value pair from new dictionary into the original dictionary, adding or replacing as needed. Syntax: <dictionary>.update(<dictionary>) Argument: 1 argument of type dictionary Return: Nothing Example:>>> School ={‘name’:’vvs’, ‘board’:cbse} >>>Student.update(School) >>>Student {‘Name’:’John’, ‘Age’:16,’Class’:12, ‘name’:’vvs’, ‘board’:cbse } 8) pop( )  Returns and deletes element from dictionary Syntax: <dictionary>.pop(<key>) Argument: 1 argument of key item Return: Value of any type Example: >>>Student. pop(‘Class’) 12 >>>Student {‘Name’: ’John’, ‘Age’:16}