SlideShare a Scribd company logo
Python   dictionary
 Python dictionary is an unordered
collection of items.
 While other compound data types have
only value as an element, a dictionary has
a key: value pair.
 Dictionaries are optimized to retrieve
values when the key is known.
 Creating a dictionary is as simple as placing items inside
curly braces {} separated by comma.
 Each element in a dictionary is represented by
a key:value pair.
 While values can be of any data type and can repeat,
keys must be of immutable type and must be unique.
mohammed.sikander@cranessoftware.com 3
 While indexing is used with other container types to access values,
dictionary uses keys. Key can be used either inside square brackets
or with the get() method.
 The difference while using get() is that it returns None instead
of KeyError, if the key is not found.
 Dictionary are mutable. We can add new items or
change the value of existing items using assignment
operator.
 If the key is already present, value gets updated, else a
new key: value pair is added to the dictionary.
 We can remove a particular item in a dictionary by using the method pop().
This method removes as item with the provided key and returns the value.
 All the items can be removed at once using the clear() method.
 We can also use the del keyword to remove individual items or the entire
dictionary itself.
Python   dictionary
 The method, popitem() can be used to remove and return an
arbitrary item (key, value) form the dictionary.
 Raises KeyError if the dictionary is empty.
Python   dictionary
 We can test if a key is in a dictionary or not using the keyword in. Notice
that membership test is for keys only, not for values.
 Using a for loop we can iterate through each
key in a dictionary.
Python   dictionary
Python   dictionary
Method Description
clear() Remove all items form the dictionary.
copy() Return a shallow copy of the dictionary.
fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v(defaults to None).
get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None).
items() Return a new view of the dictionary's items (key, value).
keys() Return a new view of the dictionary's keys.
pop(key[,d])
Remove the item with key and return its value or d if key is not found. If d is not provided
and key is not found, raises KeyError.
popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty.
setdefault(key[,d])
If key is in the dictionary, return its value. If not, insert key with a value of d and
return d (defaults to None).
update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys.
values() Return a new view of the dictionary's values
Function Description
len() Return the length (the number of items) in the dictionary.
sorted() Return a new sorted list of keys in the dictionary.
Python   dictionary
 # Definition of country and capital
 countries = ['spain', 'france', 'germany', 'norway','india']
 capitals = ['madrid', 'paris', 'berlin', 'oslo','delhi']
 # Get index of 'germany': ind_ger
 # Use ind_ger to print out capital of Germany
 I would like to print the capital of germany.
Python   dictionary
 If you know how to access a dictionary, you can also
assign a new value to it.To add a new key-value pair to
countryCapitals, you can use something like this:
countryCapitals[‘india’] = ‘delhi’
 To remove a entry from dictionary, we can use del
method.
 Remove norway
 del (countryCapitals[‘norway’])
Python   dictionary
 Create a Dictionary which records the major
cities of each state.
 {state : [major cities] }
 Dictionaries can contain key:value pairs
where the values are again dictionaries.
Python   dictionary
Ad

More Related Content

What's hot (20)

Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
Strings in C
Strings in CStrings in C
Strings in C
Kamal Acharya
 
Functions in C
Functions in CFunctions in C
Functions in C
Kamal Acharya
 
Hashing
HashingHashing
Hashing
Amar Jukuntla
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
Ninad Mankar
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Function in C program
Function in C programFunction in C program
Function in C program
Nurul Zakiah Zamri Tan
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
Edureka!
 
Data structures using c
Data structures using cData structures using c
Data structures using c
Prof. Dr. K. Adisesha
 
Hashing PPT
Hashing PPTHashing PPT
Hashing PPT
Saurabh Kumar
 
Linked list
Linked listLinked list
Linked list
KalaivaniKS1
 
Python-Inheritance.pptx
Python-Inheritance.pptxPython-Inheritance.pptx
Python-Inheritance.pptx
Karudaiyar Ganapathy
 
C tokens
C tokensC tokens
C tokens
Manu1325
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
Data Structure (Queue)
Data Structure (Queue)Data Structure (Queue)
Data Structure (Queue)
Adam Mukharil Bachtiar
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Operators in C Programming
Operators in C ProgrammingOperators in C Programming
Operators in C Programming
programming9
 
Doubly Linked List
Doubly Linked ListDoubly Linked List
Doubly Linked List
Ninad Mankar
 
Object oriented programming c++
Object oriented programming c++Object oriented programming c++
Object oriented programming c++
Ankur Pandey
 
Functions in python
Functions in pythonFunctions in python
Functions in python
colorsof
 
Binary Search Tree in Data Structure
Binary Search Tree in Data StructureBinary Search Tree in Data Structure
Binary Search Tree in Data Structure
Dharita Chokshi
 
Data Structures in Python
Data Structures in PythonData Structures in Python
Data Structures in Python
Devashish Kumar
 
Basics of C programming
Basics of C programmingBasics of C programming
Basics of C programming
avikdhupar
 
Python If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | EdurekaPython If Else | If Else Statement In Python | Edureka
Python If Else | If Else Statement In Python | Edureka
Edureka!
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 

Similar to Python dictionary (20)

Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Mapping Data Types In Python.pptx
Mapping Data Types In Python.pptxMapping Data Types In Python.pptx
Mapping Data Types In Python.pptx
Anveshbandalla
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
balewayalew
 
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
NishanSidhu2
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
Harkamal Singh
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
MSB Academy
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tuple
SukhpreetSingh519414
 
Python Sets_Dictionary.pptx
Python Sets_Dictionary.pptxPython Sets_Dictionary.pptx
Python Sets_Dictionary.pptx
M Vishnuvardhan Reddy
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
RashidFaridChishti
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
Raajendra M
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Untitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptxUntitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
Pytho dictionaries
Pytho dictionaries Pytho dictionaries
Pytho dictionaries
BMS Institute of Technology and Management
 
Python Dictionary.pptx
Python Dictionary.pptxPython Dictionary.pptx
Python Dictionary.pptx
Sanad Bhowmik
 
Dictionary
DictionaryDictionary
Dictionary
Pooja B S
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
Chapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptxChapter 14 Dictionary.pptx
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
Basic data structures in python
Basic data structures in pythonBasic data structures in python
Basic data structures in python
Celine George
 
Python Dynamic Data type List & Dictionaries
Python Dynamic Data type List & DictionariesPython Dynamic Data type List & Dictionaries
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Chapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptxChapter 3-Data structure in python programming.pptx
Chapter 3-Data structure in python programming.pptx
atharvdeshpande20
 
Mapping Data Types In Python.pptx
Mapping Data Types In Python.pptxMapping Data Types In Python.pptx
Mapping Data Types In Python.pptx
Anveshbandalla
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
balewayalew
 
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
NishanSidhu2
 
Ruby data types and objects
Ruby   data types and objectsRuby   data types and objects
Ruby data types and objects
Harkamal Singh
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
MSB Academy
 
python full notes data types string and tuple
python full notes data types string and tuplepython full notes data types string and tuple
python full notes data types string and tuple
SukhpreetSingh519414
 
DICTIONARIES (1).pptx
DICTIONARIES (1).pptxDICTIONARIES (1).pptx
DICTIONARIES (1).pptx
KalashJain27
 
Object Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptxObject Oriented Programming Using C++: C++ STL Programming.pptx
Object Oriented Programming Using C++: C++ STL Programming.pptx
RashidFaridChishti
 
Dictionaries and Sets in Python
Dictionaries and Sets in PythonDictionaries and Sets in Python
Dictionaries and Sets in Python
Raajendra M
 
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
ESIT135 Problem Solving Using Python Notes of Unit-2 and Unit-3
prasadmutkule1
 
Untitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptxUntitled dictionary in python program .pdf.pptx
Untitled dictionary in python program .pdf.pptx
SnehasisGhosh10
 
Python Dictionary.pptx
Python Dictionary.pptxPython Dictionary.pptx
Python Dictionary.pptx
Sanad Bhowmik
 
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov, Introduction to Python, Lecture4
Anton Kasyanov
 
Ad

More from Mohammed Sikander (20)

Strings in C - covers string functions
Strings in C - covers  string  functionsStrings in C - covers  string  functions
Strings in C - covers string functions
Mohammed Sikander
 
Smart Pointers, Modern Memory Management Techniques
Smart Pointers, Modern Memory Management TechniquesSmart Pointers, Modern Memory Management Techniques
Smart Pointers, Modern Memory Management Techniques
Mohammed Sikander
 
Multithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race conditionMultithreading_in_C++ - std::thread, race condition
Multithreading_in_C++ - std::thread, race condition
Mohammed Sikander
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Mohammed Sikander
 
Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
Mohammed Sikander
 
Python_Regular Expression
Python_Regular ExpressionPython_Regular Expression
Python_Regular Expression
Mohammed Sikander
 
Modern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptxModern_CPP-Range-Based For Loop.pptx
Modern_CPP-Range-Based For Loop.pptx
Mohammed Sikander
 
Modern_cpp_auto.pdf
Modern_cpp_auto.pdfModern_cpp_auto.pdf
Modern_cpp_auto.pdf
Mohammed Sikander
 
Python exception handling
Python   exception handlingPython   exception handling
Python exception handling
Mohammed Sikander
 
Python strings
Python stringsPython strings
Python strings
Mohammed Sikander
 
Python list
Python listPython list
Python list
Mohammed Sikander
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
Mohammed Sikander
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
Mohammed Sikander
 
Pointer basics
Pointer basicsPointer basics
Pointer basics
Mohammed Sikander
 
Pipe
PipePipe
Pipe
Mohammed Sikander
 
Signal
SignalSignal
Signal
Mohammed Sikander
 
File management
File managementFile management
File management
Mohammed Sikander
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
CPP Language Basics - Reference
CPP Language Basics - ReferenceCPP Language Basics - Reference
CPP Language Basics - Reference
Mohammed Sikander
 
Java arrays
Java    arraysJava    arrays
Java arrays
Mohammed Sikander
 
Ad

Recently uploaded (20)

New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
How to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 WebsiteHow to Subscribe Newsletter From Odoo 18 Website
How to Subscribe Newsletter From Odoo 18 Website
Celine George
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
World war-1(Causes & impacts at a glance) PPT by Simanchala Sarab(BABed,sem-4...
larencebapu132
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Social Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy StudentsSocial Problem-Unemployment .pptx notes for Physiotherapy Students
Social Problem-Unemployment .pptx notes for Physiotherapy Students
DrNidhiAgarwal
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public SchoolsK12 Tableau Tuesday  - Algebra Equity and Access in Atlanta Public Schools
K12 Tableau Tuesday - Algebra Equity and Access in Atlanta Public Schools
dogden2
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 

Python dictionary

  • 2.  Python dictionary is an unordered collection of items.  While other compound data types have only value as an element, a dictionary has a key: value pair.  Dictionaries are optimized to retrieve values when the key is known.
  • 3.  Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.  Each element in a dictionary is represented by a key:value pair.  While values can be of any data type and can repeat, keys must be of immutable type and must be unique. [email protected] 3
  • 4.  While indexing is used with other container types to access values, dictionary uses keys. Key can be used either inside square brackets or with the get() method.  The difference while using get() is that it returns None instead of KeyError, if the key is not found.
  • 5.  Dictionary are mutable. We can add new items or change the value of existing items using assignment operator.  If the key is already present, value gets updated, else a new key: value pair is added to the dictionary.
  • 6.  We can remove a particular item in a dictionary by using the method pop(). This method removes as item with the provided key and returns the value.  All the items can be removed at once using the clear() method.  We can also use the del keyword to remove individual items or the entire dictionary itself.
  • 8.  The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.  Raises KeyError if the dictionary is empty.
  • 10.  We can test if a key is in a dictionary or not using the keyword in. Notice that membership test is for keys only, not for values.
  • 11.  Using a for loop we can iterate through each key in a dictionary.
  • 14. Method Description clear() Remove all items form the dictionary. copy() Return a shallow copy of the dictionary. fromkeys(seq[, v]) Return a new dictionary with keys from seq and value equal to v(defaults to None). get(key[,d]) Return the value of key. If key doesnot exit, return d (defaults to None). items() Return a new view of the dictionary's items (key, value). keys() Return a new view of the dictionary's keys. pop(key[,d]) Remove the item with key and return its value or d if key is not found. If d is not provided and key is not found, raises KeyError. popitem() Remove and return an arbitary item (key, value). Raises KeyError if the dictionary is empty. setdefault(key[,d]) If key is in the dictionary, return its value. If not, insert key with a value of d and return d (defaults to None). update([other]) Update the dictionary with the key/value pairs from other, overwriting existing keys. values() Return a new view of the dictionary's values
  • 15. Function Description len() Return the length (the number of items) in the dictionary. sorted() Return a new sorted list of keys in the dictionary.
  • 17.  # Definition of country and capital  countries = ['spain', 'france', 'germany', 'norway','india']  capitals = ['madrid', 'paris', 'berlin', 'oslo','delhi']  # Get index of 'germany': ind_ger  # Use ind_ger to print out capital of Germany  I would like to print the capital of germany.
  • 19.  If you know how to access a dictionary, you can also assign a new value to it.To add a new key-value pair to countryCapitals, you can use something like this: countryCapitals[‘india’] = ‘delhi’
  • 20.  To remove a entry from dictionary, we can use del method.  Remove norway  del (countryCapitals[‘norway’])
  • 22.  Create a Dictionary which records the major cities of each state.  {state : [major cities] }
  • 23.  Dictionaries can contain key:value pairs where the values are again dictionaries.

Editor's Notes

  • #6: studentDetails = {"Name" : "Sikander" , "Course" : "PYTHON"} print(studentDetails) studentDetails["Course"] = "Data Science" print(studentDetails) studentDetails["Marks"] = 45 print(studentDetails) {'Name': 'Sikander', 'Course': 'PYTHON'} {'Name': 'Sikander', 'Course': 'Data Science'} {'Name': 'Sikander', 'Course': 'Data Science', 'Marks': 45}
  • #7: The method, popitem() can be used to remove and return an arbitrary item (key, value) form the dictionary.
  • #11: def multiply(x, y): return x * y a = 4 b = 7 operation = multiply print(operation(a, b))
  • #12: marks = {"Maths" : 45 , "Science" : 23 , "Social" : 38} for subject in marks: print(subject) for subject in marks: score = marks[subject] print(subject,":",score)
  • #14: data = "PYTHON DICTIONARY IS AMAZING" freq = {} for c in data: freq[c] = freq.get(c , 0) + 1 for key in freq: print(key , freq[key])
  • #18: # Definition of country and capital countries = ['spain', 'france', 'germany', 'norway','india'] capitals = ['madrid', 'paris', 'berlin', 'oslo','delhi'] ind_ger = countries.index('germany') print(capitals[ind_ger])
  • #21: countryCapitals = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo', 'inida':'delhi' } print(countryCapitals) #Remove Norway from dictionary del(countryCapitals['norway']) print(countryCapitals)
  • #22: countryCapitals = {'spain':'madrid', 'france':'paris', 'germany':'berlin', 'norway':'oslo', 'india':'delhi' } print(countryCapitals) #To search if a particular country is there in dictionary key = input("Enter the country to search : ") if (key in countryCapitals) : print('Entry present - Capital = ' , countryCapitals[key]) else: print('The specified country not present')
  • #23: majorcities = {'karnataka' : ['bengaluru' , 'mysore' , 'hubli'] , 'tamilnadu' : ['chennai' , 'coimbatore' , 'madurai'] , 'maharashtra' : ['mumbai' , 'pune' ] } print(majorcities) print('\nCities of Tamilnadu') print(majorcities['tamilnadu']) print('\nDifferent states ') print(majorcities.keys())
  • #24: Dictionariception Remember lists? They could contain anything, even other lists. Well, for dictionaries the same holds. Dictionaries can contain key:value pairs where the values are again dictionaries. As an example, have a look at the script where another version of europe - the dictionary you've been working with all along - is coded. The keys are still the country names, but the values are dictionaries that contain more information than just the capital. It's perfectly possible to chain square brackets to select elements. To fetch the population for Spain from europe, for example, you need: europe['spain']['population']