SlideShare a Scribd company logo
An Introduction To Software
Development Using Python
Spring Semester, 2015
Class #22:
Dictionaries
What Is A Dictionary?
• A dictionary is a container that keeps
associations between keys and values.
• Keys are unique, but a value may be
associated with several keys.
John
Mike
Ann
Mary
$15,000
$12,000
$30,000
Keys Values
Image Credit: pixgood.com
What Is A Dictionary?
• The dictionary structure is also known as a
map because it maps a unique key to a value.
• It stores the keys, values, and the associations
between them.
Image Credit: www.clipartpanda.com
Creating Dictionaries
• Each key/value pair is separated by a colon.
• You enclose the key/value pairs in braces,
just as you would when forming a set.
• When the braces contain key/value pairs, they
denote a dictionary, not a set.
• The only ambiguous case is an empty {}. By convention, it denotes an
empty dictionary, not an empty set.
• You can create a duplicate copy of a dictionary using the dict function:
oldSalaries = dict(salaries)
salaries = { “John": 15000, “Ann": 30000, “Mike": 12000, “Mary": 15000 }
Image Credit: www.clipartpal.com
Accessing Dictionary Values
• The subscript operator [] is used to return the value associated with a key.
• The statement:
print(“Ann’s salary is", salaries[“Ann"])
prints 30000
• Note that the dictionary is not a sequence-type container like a list.
• Even though the subscript operator is used with a dictionary, you cannot
access the items by index or position.
• A value can only be accessed using its associated key
Image Credit: www.clker.com
Searching For Keys
• The key supplied to the subscript operator must be a valid key
in the dictionary or a KeyError exception will be raised.
• To find out whether a key is present in the dictionary, use the
in (or not in) operator:
if “Ann" in salaries :
print(“Ann’s salary is", salaries[“Ann”])
else :
print(“Ann’s salary is not in my list.”)
Image Credit: www.clipartpanda.com
Default Value
• Often, you want to use a default value if a key is not present.
For example, if there is no salary for Mike, you want to get an
average salary instead.
• Instead of using the in operator, you can simply call the get
method and pass the key and a default value. The default
value is returned if there is no matching key.
number = salaries.get(“Mike", 17000)
print(“Salary: " + number)
Image Credit: www.clker.com
Adding and Modifying Items
• You can change a dictionary’s contents after it has been
created.
• You can add a new item using the subscript operator [] much
as you would with a list:
salaries["Lisa"] = 25000
• To change the value associated with a given key, set a new
value using the [] operator on an existing key:
salaries["Lisa"] = 17000
Image Credit: www.articulate.com
Another Way To Create
A Dictionary
• Sometimes you may not know which items will be contained
in the dictionary when it’s created.
• You can create an empty dictionary like this:
salaries = {}
• and add new items as needed:
salaries["John"] = 15000
salaries["Ann"] = 30000
salaries["Mike"] = 12000
salaries["Mary"] = 15000
Image Credit: www.clipartof.com
Removing Items
• To remove an item from a dictionary, call the pop method
with the key as the argument:
salaries.pop(“Mike")
• This removes the entire item, both the key and its associated
value.
• The pop method returns the value of the item being removed,
so you can use it or store it in a variable:
mikesSalary = salaries.pop(“Mike")
Image Credit: imgbuddy.com
Avoiding Removal Errors
• If the key is not in the dictionary, the pop method raises a
KeyError exception.
• To prevent the exception from being raised, you can test for
the key in the dictionary:
if "Mike" in salaries :
contacts.pop("Mike")
Image Credit: pixabay.com
Traversing a Dictionary
• You can iterate over the individual keys in a dictionary using a
for loop:
print(“Salaries:")
for key in salaries :
print(key)
• The result of this code fragment is shown below:
Salaries:
John
Ann
Mike
Mary
• Note that the dictionary stores its items in an order that is optimized for
efficiency, which may not be the order in which they were added.
Image Credit: tebelrpg.wordpress.com
Different Ways Of Doing
The Same Thing
• Lists
– prerequisites = [“COP 2271c”, “Introduction to Computation
and Programming”, 3]
– print(values[5]) # Prints the element at index 5
• Sets
– cheesePizza = {“Creamy garlic”, “Parmesan sauce”,
“Cheese”, “Toasted Parmesan”}
– if "Toasted Parmesan" in cheesePizza :
• Dictionaries
– salaries = {"John": 15000, "Ann": 30000, "Mike": 12000,
"Mary": 15000 }
– print("Ann’s salary is", salaries["Ann"])
Image Credit: www.clipartillustration.com
What’s In Your Python Toolbox?
print() math strings I/O IF/Else elif While For
DictionaryLists And/Or/Not Functions Files ExceptionSets
What We Covered Today
1. Creating Dictionaries
2. Accessing Dictionaries
3. Searching Dictionaries
4. Removing Items
Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
What We’ll Be Covering Next Time
1. External Libraries
Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

More Related Content

Similar to An Introduction To Python - Dictionaries

An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
Blue Elephant Consulting
 
Practical Machine Learning and Rails Part2
Practical Machine Learning and Rails Part2Practical Machine Learning and Rails Part2
Practical Machine Learning and Rails Part2
ryanstout
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
Christopher Adams
 
Casablanca SharePoint Days Power User Search Tips
Casablanca SharePoint Days Power User Search TipsCasablanca SharePoint Days Power User Search Tips
Casablanca SharePoint Days Power User Search Tips
Joel Oleson
 
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
Vikram Nandini
 
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
Lucidworks
 
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
 
Excel basics for everyday use part two
Excel basics for everyday use part twoExcel basics for everyday use part two
Excel basics for everyday use part two
Kevin McLogan
 
Luminate Online Best Practices for Beginners
Luminate Online Best Practices for BeginnersLuminate Online Best Practices for Beginners
Luminate Online Best Practices for Beginners
Blackbaud
 
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
yashar Aliabasi
 
Web Technology - PHP Arrays
Web Technology - PHP ArraysWeb Technology - PHP Arrays
Web Technology - PHP Arrays
Tarang Desai
 
Typescript-7 (1).pptx
Typescript-7 (1).pptxTypescript-7 (1).pptx
Typescript-7 (1).pptx
SachinSonawane100
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
TJ Stalcup
 
Mariia Havrylovych "Active learning and weak supervision in NLP projects"
Mariia Havrylovych "Active learning and weak supervision in NLP projects"Mariia Havrylovych "Active learning and weak supervision in NLP projects"
Mariia Havrylovych "Active learning and weak supervision in NLP projects"
Fwdays
 
xai basic solutions , with some examples and formulas
xai basic solutions , with some examples and formulasxai basic solutions , with some examples and formulas
xai basic solutions , with some examples and formulas
Royi Itzhak
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
Blue Elephant Consulting
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
Blue Elephant Consulting
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
TMARAGATHAM
 
Dictionaries
DictionariesDictionaries
Dictionaries
aiclub_slides
 

Similar to An Introduction To Python - Dictionaries (19)

An Introduction To Python - FOR Loop
An Introduction To Python - FOR LoopAn Introduction To Python - FOR Loop
An Introduction To Python - FOR Loop
 
Practical Machine Learning and Rails Part2
Practical Machine Learning and Rails Part2Practical Machine Learning and Rails Part2
Practical Machine Learning and Rails Part2
 
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
A Related Matter: Optimizing your webapp by using django-debug-toolbar, selec...
 
Casablanca SharePoint Days Power User Search Tips
Casablanca SharePoint Days Power User Search TipsCasablanca SharePoint Days Power User Search Tips
Casablanca SharePoint Days Power User Search Tips
 
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
 
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
Implementing Conceptual Search in Solr using LSA and Word2Vec: Presented by S...
 
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
 
Excel basics for everyday use part two
Excel basics for everyday use part twoExcel basics for everyday use part two
Excel basics for everyday use part two
 
Luminate Online Best Practices for Beginners
Luminate Online Best Practices for BeginnersLuminate Online Best Practices for Beginners
Luminate Online Best Practices for Beginners
 
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
 
Web Technology - PHP Arrays
Web Technology - PHP ArraysWeb Technology - PHP Arrays
Web Technology - PHP Arrays
 
Typescript-7 (1).pptx
Typescript-7 (1).pptxTypescript-7 (1).pptx
Typescript-7 (1).pptx
 
Thinkful - Intro to JavaScript
Thinkful - Intro to JavaScriptThinkful - Intro to JavaScript
Thinkful - Intro to JavaScript
 
Mariia Havrylovych "Active learning and weak supervision in NLP projects"
Mariia Havrylovych "Active learning and weak supervision in NLP projects"Mariia Havrylovych "Active learning and weak supervision in NLP projects"
Mariia Havrylovych "Active learning and weak supervision in NLP projects"
 
xai basic solutions , with some examples and formulas
xai basic solutions , with some examples and formulasxai basic solutions , with some examples and formulas
xai basic solutions , with some examples and formulas
 
An Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List AlgorithmsAn Introduction To Python - Tables, List Algorithms
An Introduction To Python - Tables, List Algorithms
 
Intro To C++ - Class #19: Functions
Intro To C++ - Class #19: FunctionsIntro To C++ - Class #19: Functions
Intro To C++ - Class #19: Functions
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Dictionaries
DictionariesDictionaries
Dictionaries
 

Recently uploaded

Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
National Information Standards Organization (NISO)
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
Nguyen Thanh Tu Collection
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
EduSkills OECD
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
Celine George
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
MJDuyan
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
Steve Thomason
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
Nguyen Thanh Tu Collection
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
giancarloi8888
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
zuzanka
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
Jyoti Chand
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
HajraNaeem15
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
GeorgeMilliken2
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
Nguyen Thanh Tu Collection
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
S. Raj Kumar
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
National Information Standards Organization (NISO)
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
TechSoup
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
siemaillard
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
Himanshu Rai
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
Nicholas Montgomery
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Vivekanand Anglo Vedic Academy
 

Recently uploaded (20)

Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"Benner "Expanding Pathways to Publishing Careers"
Benner "Expanding Pathways to Publishing Careers"
 
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
BÀI TẬP DẠY THÊM TIẾNG ANH LỚP 7 CẢ NĂM FRIENDS PLUS SÁCH CHÂN TRỜI SÁNG TẠO ...
 
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptxBeyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
Beyond Degrees - Empowering the Workforce in the Context of Skills-First.pptx
 
How to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 InventoryHow to Setup Warehouse & Location in Odoo 17 Inventory
How to Setup Warehouse & Location in Odoo 17 Inventory
 
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) CurriculumPhilippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
Philippine Edukasyong Pantahanan at Pangkabuhayan (EPP) Curriculum
 
A Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two HeartsA Visual Guide to 1 Samuel | A Tale of Two Hearts
A Visual Guide to 1 Samuel | A Tale of Two Hearts
 
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
BÀI TẬP BỔ TRỢ TIẾNG ANH 8 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2023-2024 (CÓ FI...
 
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdfREASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
REASIGNACION 2024 UGEL CHUPACA 2024 UGEL CHUPACA.pdf
 
SWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptxSWOT analysis in the project Keeping the Memory @live.pptx
SWOT analysis in the project Keeping the Memory @live.pptx
 
Wound healing PPT
Wound healing PPTWound healing PPT
Wound healing PPT
 
How to deliver Powerpoint Presentations.pptx
How to deliver Powerpoint  Presentations.pptxHow to deliver Powerpoint  Presentations.pptx
How to deliver Powerpoint Presentations.pptx
 
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
What is Digital Literacy? A guest blog from Andy McLaughlin, University of Ab...
 
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
BÀI TẬP BỔ TRỢ TIẾNG ANH LỚP 9 CẢ NĂM - GLOBAL SUCCESS - NĂM HỌC 2024-2025 - ...
 
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching AptitudeUGC NET Exam Paper 1- Unit 1:Teaching Aptitude
UGC NET Exam Paper 1- Unit 1:Teaching Aptitude
 
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
Jemison, MacLaughlin, and Majumder "Broadening Pathways for Editors and Authors"
 
Walmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdfWalmart Business+ and Spark Good for Nonprofits.pdf
Walmart Business+ and Spark Good for Nonprofits.pdf
 
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptxPrésentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
Présentationvvvvvvvvvvvvvvvvvvvvvvvvvvvv2.pptx
 
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem studentsRHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
RHEOLOGY Physical pharmaceutics-II notes for B.pharm 4th sem students
 
writing about opinions about Australia the movie
writing about opinions about Australia the moviewriting about opinions about Australia the movie
writing about opinions about Australia the movie
 
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDFLifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
Lifelines of National Economy chapter for Class 10 STUDY MATERIAL PDF
 

An Introduction To Python - Dictionaries

  • 1. An Introduction To Software Development Using Python Spring Semester, 2015 Class #22: Dictionaries
  • 2. What Is A Dictionary? • A dictionary is a container that keeps associations between keys and values. • Keys are unique, but a value may be associated with several keys. John Mike Ann Mary $15,000 $12,000 $30,000 Keys Values Image Credit: pixgood.com
  • 3. What Is A Dictionary? • The dictionary structure is also known as a map because it maps a unique key to a value. • It stores the keys, values, and the associations between them. Image Credit: www.clipartpanda.com
  • 4. Creating Dictionaries • Each key/value pair is separated by a colon. • You enclose the key/value pairs in braces, just as you would when forming a set. • When the braces contain key/value pairs, they denote a dictionary, not a set. • The only ambiguous case is an empty {}. By convention, it denotes an empty dictionary, not an empty set. • You can create a duplicate copy of a dictionary using the dict function: oldSalaries = dict(salaries) salaries = { “John": 15000, “Ann": 30000, “Mike": 12000, “Mary": 15000 } Image Credit: www.clipartpal.com
  • 5. Accessing Dictionary Values • The subscript operator [] is used to return the value associated with a key. • The statement: print(“Ann’s salary is", salaries[“Ann"]) prints 30000 • Note that the dictionary is not a sequence-type container like a list. • Even though the subscript operator is used with a dictionary, you cannot access the items by index or position. • A value can only be accessed using its associated key Image Credit: www.clker.com
  • 6. Searching For Keys • The key supplied to the subscript operator must be a valid key in the dictionary or a KeyError exception will be raised. • To find out whether a key is present in the dictionary, use the in (or not in) operator: if “Ann" in salaries : print(“Ann’s salary is", salaries[“Ann”]) else : print(“Ann’s salary is not in my list.”) Image Credit: www.clipartpanda.com
  • 7. Default Value • Often, you want to use a default value if a key is not present. For example, if there is no salary for Mike, you want to get an average salary instead. • Instead of using the in operator, you can simply call the get method and pass the key and a default value. The default value is returned if there is no matching key. number = salaries.get(“Mike", 17000) print(“Salary: " + number) Image Credit: www.clker.com
  • 8. Adding and Modifying Items • You can change a dictionary’s contents after it has been created. • You can add a new item using the subscript operator [] much as you would with a list: salaries["Lisa"] = 25000 • To change the value associated with a given key, set a new value using the [] operator on an existing key: salaries["Lisa"] = 17000 Image Credit: www.articulate.com
  • 9. Another Way To Create A Dictionary • Sometimes you may not know which items will be contained in the dictionary when it’s created. • You can create an empty dictionary like this: salaries = {} • and add new items as needed: salaries["John"] = 15000 salaries["Ann"] = 30000 salaries["Mike"] = 12000 salaries["Mary"] = 15000 Image Credit: www.clipartof.com
  • 10. Removing Items • To remove an item from a dictionary, call the pop method with the key as the argument: salaries.pop(“Mike") • This removes the entire item, both the key and its associated value. • The pop method returns the value of the item being removed, so you can use it or store it in a variable: mikesSalary = salaries.pop(“Mike") Image Credit: imgbuddy.com
  • 11. Avoiding Removal Errors • If the key is not in the dictionary, the pop method raises a KeyError exception. • To prevent the exception from being raised, you can test for the key in the dictionary: if "Mike" in salaries : contacts.pop("Mike") Image Credit: pixabay.com
  • 12. Traversing a Dictionary • You can iterate over the individual keys in a dictionary using a for loop: print(“Salaries:") for key in salaries : print(key) • The result of this code fragment is shown below: Salaries: John Ann Mike Mary • Note that the dictionary stores its items in an order that is optimized for efficiency, which may not be the order in which they were added. Image Credit: tebelrpg.wordpress.com
  • 13. Different Ways Of Doing The Same Thing • Lists – prerequisites = [“COP 2271c”, “Introduction to Computation and Programming”, 3] – print(values[5]) # Prints the element at index 5 • Sets – cheesePizza = {“Creamy garlic”, “Parmesan sauce”, “Cheese”, “Toasted Parmesan”} – if "Toasted Parmesan" in cheesePizza : • Dictionaries – salaries = {"John": 15000, "Ann": 30000, "Mike": 12000, "Mary": 15000 } – print("Ann’s salary is", salaries["Ann"]) Image Credit: www.clipartillustration.com
  • 14. What’s In Your Python Toolbox? print() math strings I/O IF/Else elif While For DictionaryLists And/Or/Not Functions Files ExceptionSets
  • 15. What We Covered Today 1. Creating Dictionaries 2. Accessing Dictionaries 3. Searching Dictionaries 4. Removing Items Image Credit: http://www.tswdj.com/blog/2011/05/17/the-grooms-checklist/
  • 16. What We’ll Be Covering Next Time 1. External Libraries Image Credit: http://merchantblog.thefind.com/2011/01/merchant-newsletter/resolve-to-take-advantage-of-these-5-e-commerce-trends/attachment/crystal-ball-fullsize/

Editor's Notes

  1. New name for the class I know what this means Technical professionals are who get hired This means much more than just having a narrow vertical knowledge of some subject area. It means that you know how to produce an outcome that I value. I’m willing to pay you to do that.