SlideShare a Scribd company logo
1 of 24
http://www.skillbrew.com
/SkillbrewTalent brewed by the
industry itself
Dictionaries
Pavan Verma
@YinYangPavan
Founder, P3 InfoTech Solutions Pvt. Ltd.
Python Programming Essentials
1
© SkillBrew http://skillbrew.com
What is a dictionary
2
• Dictionaries are collections of items that have
a “key” and a “value”
• Like a list is indexed by a number from 0 to len-
1, dictionaries are indexed by the keys
© SkillBrew http://skillbrew.com
Sample use cases of dictionary
 Storing a record of information as key-
value pairs
 Example: Contact list
3
© SkillBrew http://skillbrew.com
Creating a dictionary
4
mydict = {
'one': 1,
'two': 2,
}
print mydict
Output:
{'two': 2, 'one': 1}
Syntax
mydict = {
key1: value1,
key2: value2,
}
© SkillBrew http://skillbrew.com
Accessing elements of a dictionary
5
mydict = {
'one': 1,
'two': 2,
}
print mydict['one']
print mydict['two']
Output:
1
2
dict[key]
© SkillBrew http://skillbrew.com
Accessing elements of a dictionary (2)
6
mydict = {
'one': 1,
'two': 2,
}
print mydict['three']
Output:
KeyError: 'three' Accessing a key that does
not exist throws
KeyError
© SkillBrew http://skillbrew.com
Key types
7
Keys can be of any immutable type
1. Strings
2. Numbers
3. Tuples
© SkillBrew http://skillbrew.com
Key types (2)
8
mydict = {
'one': 1,
'two': 2,
}
Strings as keys
© SkillBrew http://skillbrew.com
Key types (3)
9
points = {
(1, 2): 10,
(3, 4): 20,
}
Tuples as keys
mydict = {
1: 'one',
2: 'two',
}
Numbers as keys
© SkillBrew http://skillbrew.com
Tuples as keys
10
• Tuples can be used as keys if they contain only other
immutable types – strings, numbers, or tuples
• If a tuple contains any mutable type, it cannot be used
as a key
mydict = {
([1, 2, 3], 4): 'one',
}
TypeError: unhashable type: 'list'
© SkillBrew http://skillbrew.com
Accessing keys
11
contact = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": True,
}
print contact.keys()
['salary', 'last', 'age', 'sex', 'registered',
'first']
dict.keys() gives an
unordered list of keys in a
dictionary
© SkillBrew http://skillbrew.com
Accessing values
12
contact = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": True,
}
print contact.values()
[70000, 'Doe', 39, 'M', True, 'John']
dict.values() gives an
unordered list of values in
dictionary
© SkillBrew http://skillbrew.com
Updating an element
13
contact = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 70000,
"registered": True,
}
contact['salary'] = 90000
print contact
Output:
{'salary': 90000, 'last': 'Doe', 'age': 39, 'sex': 'M',
'registered': True, 'first': 'John'}
dict[key] = newvalue
© SkillBrew http://skillbrew.com
Deleting an element
14
contact = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 90000,
"registered": True,
}
del contact['last']
print contact
Output:
{'salary': 90000, 'age': 39, 'sex': 'M', 'registered': True,
'first': 'John'}
del dict[key]
© SkillBrew http://skillbrew.com
Test if a key exists in a dictionary
15
contact = {
"first": "John",
"last": "Doe",
"age": 39,
"sex": "M",
"salary": 90000,
"registered": True,
}
print 'first' in contact
Output: True
print 'second' in contact
Output: False
Use in operator to test weather
a key exists or not
© SkillBrew http://skillbrew.com
Loop over a dictionary
16
for key in contact:
print key
Output:
salary
age
sex
registered
first
By default looping over a
dictionary, gives access to all the
keys
© SkillBrew http://skillbrew.com
Loop over a dictionary (2)
17
for key in contact.iterkeys():
print key
Output:
salary
age
sex
registered
first
dict.iterkeys():use this
to iterate over keys of a
dictionary
© SkillBrew http://skillbrew.com
Loop over a dictionary (3)
18
for key in contact.itervalues():
print key
Output:
90000
39
M
True
John
dict.itervalues(): use
this to iterate over values of a
dictionary
© SkillBrew http://skillbrew.com
Loop over a dictionary (4)
19
for key, value in contact.iteritems():
print key, value
Output:
salary 90000
age 39
sex M
registered True
first John
dict.iteritems(): use
this to iterate over both keys and
values
© SkillBrew http://skillbrew.com
Example: Contact information
contacts = [
{'name': 'Pavan Verma',
'mobile': '9999900000',
'email': 'pavan@p3infotech.in', }
{'name': 'Sahil Chug',
'mobile': '9999900001',
'email': 'sahil@p3infotech.in', }
{'name': 'Abijith MG',
'mobile': '9999900007',
'email': 'abijith@p3infotech.in', }
]
20
© SkillBrew http://skillbrew.com
Example: Contact information (2)
contacts = {
1: {'name': 'Pavan Verma',
'mobile': '9999900000',
'email': 'pavan@p3infotech.in', }
2: {'name': 'Sahil Chug',
'mobile': '9999900001',
'email': 'sahil@p3infotech.in', }
8: {'name': 'Abijith MG',
'mobile': '9999900007',
'email': 'abijith@p3infotech.in', }
}
21
© SkillBrew http://skillbrew.com
Summary
 What is a dictionary
 Creating a dictionary
 Accessing elements of a dictionary
 Key types
 Tuples as keys
 Iterating over dictionary
22
© SkillBrew http://skillbrew.com
References
 Dictionaries tutorial
http://www.tutorialspoint.com/python/python_dictionary.htm
 Dictionaries in detail in python docs
http://docs.python.org/2/library/stdtypes.html#mapping-
types-dict
23
24

More Related Content

Similar to Python Programming Essentials - M14 - Dictionaries

Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 MinutesKarel Minarik
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7Megha V
 
Building Services With gRPC, Docker and Go
Building Services With gRPC, Docker and GoBuilding Services With gRPC, Docker and Go
Building Services With gRPC, Docker and GoMartin Kess
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPiMasters
 
Constance et qualité du code dans une équipe - Rémi Prévost
Constance et qualité du code dans une équipe - Rémi PrévostConstance et qualité du code dans une équipe - Rémi Prévost
Constance et qualité du code dans une équipe - Rémi PrévostWeb à Québec
 
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...DynamicInfraDays
 
Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™Nicola Iarocci
 
Contacto server API in PHP
Contacto server API in PHPContacto server API in PHP
Contacto server API in PHPHem Shrestha
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBMongoDB
 
Eurosentiment - Developing a new service
Eurosentiment - Developing a new serviceEurosentiment - Developing a new service
Eurosentiment - Developing a new servicemario_munoz
 

Similar to Python Programming Essentials - M14 - Dictionaries (13)

Elasticsearch in 15 Minutes
Elasticsearch in 15 MinutesElasticsearch in 15 Minutes
Elasticsearch in 15 Minutes
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
 
Building Services With gRPC, Docker and Go
Building Services With gRPC, Docker and GoBuilding Services With gRPC, Docker and Go
Building Services With gRPC, Docker and Go
 
Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
 
Mashing Up The Guardian
Mashing Up The GuardianMashing Up The Guardian
Mashing Up The Guardian
 
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHPPHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
PHP Experience 2016 - [Workshop] Elastic Search: Turbinando sua aplicação PHP
 
Constance et qualité du code dans une équipe - Rémi Prévost
Constance et qualité du code dans une équipe - Rémi PrévostConstance et qualité du code dans une équipe - Rémi Prévost
Constance et qualité du code dans une équipe - Rémi Prévost
 
Python slide
Python slidePython slide
Python slide
 
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
ContainerDays NYC 2016: "OpenWhisk: A Serverless Computing Platform" (Rodric ...
 
Eve - REST API for Humans™
Eve - REST API for Humans™Eve - REST API for Humans™
Eve - REST API for Humans™
 
Contacto server API in PHP
Contacto server API in PHPContacto server API in PHP
Contacto server API in PHP
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
 
Eurosentiment - Developing a new service
Eurosentiment - Developing a new serviceEurosentiment - Developing a new service
Eurosentiment - Developing a new service
 

More from P3 InfoTech Solutions Pvt. Ltd.

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesP3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsP3 InfoTech Solutions Pvt. Ltd.
 

More from P3 InfoTech Solutions Pvt. Ltd. (20)

Python Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web DevelopmentPython Programming Essentials - M44 - Overview of Web Development
Python Programming Essentials - M44 - Overview of Web Development
 
Python Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External ProgramsPython Programming Essentials - M40 - Invoking External Programs
Python Programming Essentials - M40 - Invoking External Programs
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
 
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc ConceptsPython Programming Essentials - M37 - Brief Overview of Misc Concepts
Python Programming Essentials - M37 - Brief Overview of Misc Concepts
 
Python Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & GeneratorsPython Programming Essentials - M35 - Iterators & Generators
Python Programming Essentials - M35 - Iterators & Generators
 
Python Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List ComprehensionsPython Programming Essentials - M34 - List Comprehensions
Python Programming Essentials - M34 - List Comprehensions
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
 
Python Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and FilesPython Programming Essentials - M29 - Python Interpreter and Files
Python Programming Essentials - M29 - Python Interpreter and Files
 
Python Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdbPython Programming Essentials - M28 - Debugging with pdb
Python Programming Essentials - M28 - Debugging with pdb
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
 
Python Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modulesPython Programming Essentials - M25 - os and sys modules
Python Programming Essentials - M25 - os and sys modules
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
 
Python Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception HandlingPython Programming Essentials - M21 - Exception Handling
Python Programming Essentials - M21 - Exception Handling
 
Python Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and ObjectsPython Programming Essentials - M20 - Classes and Objects
Python Programming Essentials - M20 - Classes and Objects
 
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
Python Programming Essentials - M19 - Namespaces, Global Variables and Docstr...
 
Python Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and PackagesPython Programming Essentials - M18 - Modules and Packages
Python Programming Essentials - M18 - Modules and Packages
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
 
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 

Recently uploaded

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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 2024The Digital Insurer
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
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...Igalia
 
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 Processorsdebabhi2
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
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.pptxEarley Information Science
 

Recently uploaded (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
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...
 
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
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 

Python Programming Essentials - M14 - Dictionaries

  • 1. http://www.skillbrew.com /SkillbrewTalent brewed by the industry itself Dictionaries Pavan Verma @YinYangPavan Founder, P3 InfoTech Solutions Pvt. Ltd. Python Programming Essentials 1
  • 2. © SkillBrew http://skillbrew.com What is a dictionary 2 • Dictionaries are collections of items that have a “key” and a “value” • Like a list is indexed by a number from 0 to len- 1, dictionaries are indexed by the keys
  • 3. © SkillBrew http://skillbrew.com Sample use cases of dictionary  Storing a record of information as key- value pairs  Example: Contact list 3
  • 4. © SkillBrew http://skillbrew.com Creating a dictionary 4 mydict = { 'one': 1, 'two': 2, } print mydict Output: {'two': 2, 'one': 1} Syntax mydict = { key1: value1, key2: value2, }
  • 5. © SkillBrew http://skillbrew.com Accessing elements of a dictionary 5 mydict = { 'one': 1, 'two': 2, } print mydict['one'] print mydict['two'] Output: 1 2 dict[key]
  • 6. © SkillBrew http://skillbrew.com Accessing elements of a dictionary (2) 6 mydict = { 'one': 1, 'two': 2, } print mydict['three'] Output: KeyError: 'three' Accessing a key that does not exist throws KeyError
  • 7. © SkillBrew http://skillbrew.com Key types 7 Keys can be of any immutable type 1. Strings 2. Numbers 3. Tuples
  • 8. © SkillBrew http://skillbrew.com Key types (2) 8 mydict = { 'one': 1, 'two': 2, } Strings as keys
  • 9. © SkillBrew http://skillbrew.com Key types (3) 9 points = { (1, 2): 10, (3, 4): 20, } Tuples as keys mydict = { 1: 'one', 2: 'two', } Numbers as keys
  • 10. © SkillBrew http://skillbrew.com Tuples as keys 10 • Tuples can be used as keys if they contain only other immutable types – strings, numbers, or tuples • If a tuple contains any mutable type, it cannot be used as a key mydict = { ([1, 2, 3], 4): 'one', } TypeError: unhashable type: 'list'
  • 11. © SkillBrew http://skillbrew.com Accessing keys 11 contact = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 70000, "registered": True, } print contact.keys() ['salary', 'last', 'age', 'sex', 'registered', 'first'] dict.keys() gives an unordered list of keys in a dictionary
  • 12. © SkillBrew http://skillbrew.com Accessing values 12 contact = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 70000, "registered": True, } print contact.values() [70000, 'Doe', 39, 'M', True, 'John'] dict.values() gives an unordered list of values in dictionary
  • 13. © SkillBrew http://skillbrew.com Updating an element 13 contact = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 70000, "registered": True, } contact['salary'] = 90000 print contact Output: {'salary': 90000, 'last': 'Doe', 'age': 39, 'sex': 'M', 'registered': True, 'first': 'John'} dict[key] = newvalue
  • 14. © SkillBrew http://skillbrew.com Deleting an element 14 contact = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 90000, "registered": True, } del contact['last'] print contact Output: {'salary': 90000, 'age': 39, 'sex': 'M', 'registered': True, 'first': 'John'} del dict[key]
  • 15. © SkillBrew http://skillbrew.com Test if a key exists in a dictionary 15 contact = { "first": "John", "last": "Doe", "age": 39, "sex": "M", "salary": 90000, "registered": True, } print 'first' in contact Output: True print 'second' in contact Output: False Use in operator to test weather a key exists or not
  • 16. © SkillBrew http://skillbrew.com Loop over a dictionary 16 for key in contact: print key Output: salary age sex registered first By default looping over a dictionary, gives access to all the keys
  • 17. © SkillBrew http://skillbrew.com Loop over a dictionary (2) 17 for key in contact.iterkeys(): print key Output: salary age sex registered first dict.iterkeys():use this to iterate over keys of a dictionary
  • 18. © SkillBrew http://skillbrew.com Loop over a dictionary (3) 18 for key in contact.itervalues(): print key Output: 90000 39 M True John dict.itervalues(): use this to iterate over values of a dictionary
  • 19. © SkillBrew http://skillbrew.com Loop over a dictionary (4) 19 for key, value in contact.iteritems(): print key, value Output: salary 90000 age 39 sex M registered True first John dict.iteritems(): use this to iterate over both keys and values
  • 20. © SkillBrew http://skillbrew.com Example: Contact information contacts = [ {'name': 'Pavan Verma', 'mobile': '9999900000', 'email': 'pavan@p3infotech.in', } {'name': 'Sahil Chug', 'mobile': '9999900001', 'email': 'sahil@p3infotech.in', } {'name': 'Abijith MG', 'mobile': '9999900007', 'email': 'abijith@p3infotech.in', } ] 20
  • 21. © SkillBrew http://skillbrew.com Example: Contact information (2) contacts = { 1: {'name': 'Pavan Verma', 'mobile': '9999900000', 'email': 'pavan@p3infotech.in', } 2: {'name': 'Sahil Chug', 'mobile': '9999900001', 'email': 'sahil@p3infotech.in', } 8: {'name': 'Abijith MG', 'mobile': '9999900007', 'email': 'abijith@p3infotech.in', } } 21
  • 22. © SkillBrew http://skillbrew.com Summary  What is a dictionary  Creating a dictionary  Accessing elements of a dictionary  Key types  Tuples as keys  Iterating over dictionary 22
  • 23. © SkillBrew http://skillbrew.com References  Dictionaries tutorial http://www.tutorialspoint.com/python/python_dictionary.htm  Dictionaries in detail in python docs http://docs.python.org/2/library/stdtypes.html#mapping- types-dict 23
  • 24. 24

Editor's Notes

  1. Dictionaries are equivalent to Hash Data Structure in some languages
  2. Contact list * Can directly get a person’s number from his name, without searching * Contact records can have lot of fields, many of which might be empty. If we represent contact record as a list/tuple, will be difficult to keep track of the fields. Better to represent the information a dictionary of dictionaries or as list of dictionaries
  3. Since mydict has a List as its element , it is not allowed as dictionary key. The list may change in future hence inappropriate for a dict key
  4. Use del operator to delete an element in dictionary