SlideShare une entreprise Scribd logo
1  sur  17
Dictionary
Python Built-in Data Type
What does Dict do?

• Collection of information
• Query information
• Add/Update Information

                              Dictionary
                              Introduction
Initialization

•   aDict = {}

•   aDict = dict()

•   aDict = { “apple” : 3
              “banana”: 5 }


                              Dictionary
                              Introduction
Initialization

•   aDict = {}

•   aDict = dict()

•   aDict = { “apple” : 3
              “banana”: 5 }
                 Key
                              Dictionary
                              Introduction
Initialization

•   aDict = {}

•   aDict = dict()

•   aDict = { “apple” : 3
              “banana”: 5 }
                 Key   Value
                               Dictionary
                               Introduction
Query
>>> aDict["apple"]
3
>>> aDict.keys()
dict_keys(['apple', 'banana'])
>>> aDict.values()
dict_values([3, 5])
>>> aDict.items()
dict_items([('apple', 3), ('banana', 5)])

                                    Dictionary
                                    Introduction
Query
• Call each item with for-loop statement
   >>> for x in aDict.keys():
   ...    print(x)
   ...
   apple
   banana



                                       Dictionary
                                       Introduction
Add
• Directly add a item to dictionary
  >>> aDict
  {'apple': 5, 'banana': 5}
  >>> aDict['waterfruit'] = 8
  >>> aDict
  {'waterfruit': 8, 'apple': 5, 'banana': 5}




                                        Dictionary
                                        Introduction
Update
•   Update the content of the dictionary
•   aDict.update(<dict>)

•   Example:
     >>> aDict.update({'apple':5})
     >>> aDict.update({'chocolate':10})
     >>> aDict
     {'chocolate': 10, 'apple': 5, 'banana': 5}



                                        Dictionary
                                        Introduction
Delete

• Remove a item from the dictionary
•  del aDict[“apple”]




                                      Dictionary
                                      Introduction
Practice
• Phone book
• Functions:
 • Print a phone number
 • Add a phone number
 • Remove a phone number
 • Lookup a phone number
                           Dictionary
                           Introduction
Practice
def print_menu():
    print('1. Print Phone Numbers')
    print('2. Add a Phone Number')
    print('3. Remove a Phone Number')
    print('4. Lookup a Phone Number')
    print('5. Quit')
    print()



                                  Dictionary
                                  Introduction
Practice
numbers = {}
menu_choice = 0
print_menu()
while menu_choice != 5:
    menu_choice = int(input("Type in a number (1-5): "))
    if menu_choice == 1:
        pass
    elif menu_choice == 2:
        pass
    elif menu_choice == 3:      http://goo.gl/A9xDr
        pass
    elif menu_choice == 4:
        pass
    elif menu_choice != 5:
        print_menu()
                                                Dictionary
                                                Introduction
Print
if menu_choice == 1:
     print("Telephone Numbers:")
     for x in numbers.keys():
         print("Name: ", x, "tNumber:", numbers[x])
     print()




                                             Dictionary
                                             Introduction
Add

elif menu_choice == 2:
     print("Add Name and Number")
     name = input("Name: ")
     phone = input("Number: ")
     numbers[name] = phone




                                    Dictionary
                                    Introduction
Remove
elif menu_choice == 3:
        print("Remove Name and Number")
        name = input("Name: ")
        if name in numbers:
            del numbers[name]
        else:
            print(name, "was not found")




                                           Dictionary
                                           Introduction
Lookup
elif menu_choice == 4:
    print("Lookup Number")
    name = input("Name: ")
    if name in numbers:
        print("The number is", numbers[name])
    else:
        print(name, "was not found")




                                          Dictionary
                                          Introduction

Contenu connexe

Tendances

JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
PROIDEA
 

Tendances (20)

Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Lists
ListsLists
Lists
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Closure, Higher-order function in Swift
Closure, Higher-order function in SwiftClosure, Higher-order function in Swift
Closure, Higher-order function in Swift
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 
Class 4 - PHP Arrays
Class 4 - PHP ArraysClass 4 - PHP Arrays
Class 4 - PHP Arrays
 
Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)Swift에서 꼬리재귀 사용기 (Tail Recursion)
Swift에서 꼬리재귀 사용기 (Tail Recursion)
 
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with SwiftStanfy MadCode Meetup #9: Functional Programming 101 with Swift
Stanfy MadCode Meetup #9: Functional Programming 101 with Swift
 
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
JDD2015: Functional programing and Event Sourcing - a pair made in heaven - e...
 
Oop lecture8
Oop lecture8Oop lecture8
Oop lecture8
 
Python's magic methods
Python's magic methodsPython's magic methods
Python's magic methods
 
[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4[1062BPY12001] Data analysis with R / week 4
[1062BPY12001] Data analysis with R / week 4
 
Php array
Php arrayPhp array
Php array
 
Namespace and methods
Namespace and methodsNamespace and methods
Namespace and methods
 
dotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World ProtocolsdotSwift 2016 : Beyond Crusty - Real-World Protocols
dotSwift 2016 : Beyond Crusty - Real-World Protocols
 
Arrays in PHP
Arrays in PHPArrays in PHP
Arrays in PHP
 
Python3 cheatsheet
Python3 cheatsheetPython3 cheatsheet
Python3 cheatsheet
 
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
How to Become a Tree Hugger: Random Forests and Predictive Modeling for Devel...
 
R part iii
R part iiiR part iii
R part iii
 
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
Analysis of Fatal Utah Avalanches with Python. From Scraping, Analysis, to In...
 

Similaire à Python Dictionary

Similaire à Python Dictionary (20)

list and control statement.pptx
list and control statement.pptxlist and control statement.pptx
list and control statement.pptx
 
Python Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, DictionaryPython Variable Types, List, Tuple, Dictionary
Python Variable Types, List, Tuple, Dictionary
 
Python - Data Structures
Python - Data StructuresPython - Data Structures
Python - Data Structures
 
Python 101 1
Python 101   1Python 101   1
Python 101 1
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Python_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdfPython_Cheat_Sheet_Keywords_1664634397.pdf
Python_Cheat_Sheet_Keywords_1664634397.pdf
 
Farhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionariesFarhana shaikh webinar_dictionaries
Farhana shaikh webinar_dictionaries
 
Python Collection datatypes
Python Collection datatypesPython Collection datatypes
Python Collection datatypes
 
Pa1 lists subset
Pa1 lists subsetPa1 lists subset
Pa1 lists subset
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
 
Tip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python TypingTip Top Typing - A Look at Python Typing
Tip Top Typing - A Look at Python Typing
 
Introduction To Programming with Python-4
Introduction To Programming with Python-4Introduction To Programming with Python-4
Introduction To Programming with Python-4
 
Exception handling and function in python
Exception handling and function in pythonException handling and function in python
Exception handling and function in python
 
Python PCEP Tuples and Dictionaries
Python PCEP Tuples and DictionariesPython PCEP Tuples and Dictionaries
Python PCEP Tuples and Dictionaries
 
Python Programming for basic beginners.pptx
Python Programming for basic beginners.pptxPython Programming for basic beginners.pptx
Python Programming for basic beginners.pptx
 
File handling in pythan.pptx
File handling in pythan.pptxFile handling in pythan.pptx
File handling in pythan.pptx
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Session 02 python basics
Session 02 python basicsSession 02 python basics
Session 02 python basics
 
Python Dictionary
Python DictionaryPython Dictionary
Python Dictionary
 
Basics of Python programming (part 2)
Basics of Python programming (part 2)Basics of Python programming (part 2)
Basics of Python programming (part 2)
 

Plus de Colin Su

Introduction to Google Compute Engine
Introduction to Google Compute EngineIntroduction to Google Compute Engine
Introduction to Google Compute Engine
Colin Su
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
Colin Su
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
Colin Su
 
How to Speak Charms Like a Wizard
How to Speak Charms Like a WizardHow to Speak Charms Like a Wizard
How to Speak Charms Like a Wizard
Colin Su
 
房地產報告
房地產報告房地產報告
房地產報告
Colin Su
 
Facebook Python SDK - Introduction
Facebook Python SDK - IntroductionFacebook Python SDK - Introduction
Facebook Python SDK - Introduction
Colin Su
 

Plus de Colin Su (20)

Introduction to Google Compute Engine
Introduction to Google Compute EngineIntroduction to Google Compute Engine
Introduction to Google Compute Engine
 
Introduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API DevelopmentIntroduction to Google Cloud Endpoints: Speed Up Your API Development
Introduction to Google Cloud Endpoints: Speed Up Your API Development
 
Functional programming in Python
Functional programming in PythonFunctional programming in Python
Functional programming in Python
 
Web2py Code Lab
Web2py Code LabWeb2py Code Lab
Web2py Code Lab
 
A Tour of Google Cloud Platform
A Tour of Google Cloud PlatformA Tour of Google Cloud Platform
A Tour of Google Cloud Platform
 
Introduction to Facebook JavaScript & Python SDK
Introduction to Facebook JavaScript & Python SDKIntroduction to Facebook JavaScript & Python SDK
Introduction to Facebook JavaScript & Python SDK
 
Introduction to MapReduce & hadoop
Introduction to MapReduce & hadoopIntroduction to MapReduce & hadoop
Introduction to MapReduce & hadoop
 
Introduction to Google App Engine
Introduction to Google App EngineIntroduction to Google App Engine
Introduction to Google App Engine
 
Django Deployer
Django DeployerDjango Deployer
Django Deployer
 
Introduction to Google - the most natural way to learn English (English Speech)
Introduction to Google - the most natural way to learn English (English Speech)Introduction to Google - the most natural way to learn English (English Speech)
Introduction to Google - the most natural way to learn English (English Speech)
 
How to Speak Charms Like a Wizard
How to Speak Charms Like a WizardHow to Speak Charms Like a Wizard
How to Speak Charms Like a Wizard
 
房地產報告
房地產報告房地產報告
房地產報告
 
Introduction to Git
Introduction to GitIntroduction to Git
Introduction to Git
 
Introduction to Facebook Javascript SDK (NEW)
Introduction to Facebook Javascript SDK (NEW)Introduction to Facebook Javascript SDK (NEW)
Introduction to Facebook Javascript SDK (NEW)
 
Introduction to Facebook Python API
Introduction to Facebook Python APIIntroduction to Facebook Python API
Introduction to Facebook Python API
 
Facebook Python SDK - Introduction
Facebook Python SDK - IntroductionFacebook Python SDK - Introduction
Facebook Python SDK - Introduction
 
Web Programming - 1st TA Session
Web Programming - 1st TA SessionWeb Programming - 1st TA Session
Web Programming - 1st TA Session
 
Nested List Comprehension and Binary Search
Nested List Comprehension and Binary SearchNested List Comprehension and Binary Search
Nested List Comprehension and Binary Search
 
Python-List comprehension
Python-List comprehensionPython-List comprehension
Python-List comprehension
 
Python-FileIO
Python-FileIOPython-FileIO
Python-FileIO
 

Dernier

EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Dernier (20)

Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 

Python Dictionary

  • 2. What does Dict do? • Collection of information • Query information • Add/Update Information Dictionary Introduction
  • 3. Initialization • aDict = {} • aDict = dict() • aDict = { “apple” : 3 “banana”: 5 } Dictionary Introduction
  • 4. Initialization • aDict = {} • aDict = dict() • aDict = { “apple” : 3 “banana”: 5 } Key Dictionary Introduction
  • 5. Initialization • aDict = {} • aDict = dict() • aDict = { “apple” : 3 “banana”: 5 } Key Value Dictionary Introduction
  • 6. Query >>> aDict["apple"] 3 >>> aDict.keys() dict_keys(['apple', 'banana']) >>> aDict.values() dict_values([3, 5]) >>> aDict.items() dict_items([('apple', 3), ('banana', 5)]) Dictionary Introduction
  • 7. Query • Call each item with for-loop statement >>> for x in aDict.keys(): ... print(x) ... apple banana Dictionary Introduction
  • 8. Add • Directly add a item to dictionary >>> aDict {'apple': 5, 'banana': 5} >>> aDict['waterfruit'] = 8 >>> aDict {'waterfruit': 8, 'apple': 5, 'banana': 5} Dictionary Introduction
  • 9. Update • Update the content of the dictionary • aDict.update(<dict>) • Example: >>> aDict.update({'apple':5}) >>> aDict.update({'chocolate':10}) >>> aDict {'chocolate': 10, 'apple': 5, 'banana': 5} Dictionary Introduction
  • 10. Delete • Remove a item from the dictionary • del aDict[“apple”] Dictionary Introduction
  • 11. Practice • Phone book • Functions: • Print a phone number • Add a phone number • Remove a phone number • Lookup a phone number Dictionary Introduction
  • 12. Practice def print_menu(): print('1. Print Phone Numbers') print('2. Add a Phone Number') print('3. Remove a Phone Number') print('4. Lookup a Phone Number') print('5. Quit') print() Dictionary Introduction
  • 13. Practice numbers = {} menu_choice = 0 print_menu() while menu_choice != 5: menu_choice = int(input("Type in a number (1-5): ")) if menu_choice == 1: pass elif menu_choice == 2: pass elif menu_choice == 3: http://goo.gl/A9xDr pass elif menu_choice == 4: pass elif menu_choice != 5: print_menu() Dictionary Introduction
  • 14. Print if menu_choice == 1: print("Telephone Numbers:") for x in numbers.keys(): print("Name: ", x, "tNumber:", numbers[x]) print() Dictionary Introduction
  • 15. Add elif menu_choice == 2: print("Add Name and Number") name = input("Name: ") phone = input("Number: ") numbers[name] = phone Dictionary Introduction
  • 16. Remove elif menu_choice == 3: print("Remove Name and Number") name = input("Name: ") if name in numbers: del numbers[name] else: print(name, "was not found") Dictionary Introduction
  • 17. Lookup elif menu_choice == 4: print("Lookup Number") name = input("Name: ") if name in numbers: print("The number is", numbers[name]) else: print(name, "was not found") Dictionary Introduction

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n