SlideShare a Scribd company logo
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 Minutes
Karel Minarik
 
Python programming –part 7
Python programming –part 7Python programming –part 7
Python programming –part 7
Megha 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 Go
Martin Kess
 
Introducing LINQ
Introducing LINQIntroducing LINQ
Introducing LINQ
LearnNowOnline
 
Mashing Up The Guardian
Mashing Up The GuardianMashing Up The Guardian
Mashing Up The Guardian
Michael Brunton-Spall
 
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
iMasters
 
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
Web à Québec
 
Python slide
Python slidePython 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 ...
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 PHP
Hem Shrestha
 
Fast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDBFast REST APIs Development with MongoDB
Fast REST APIs Development with MongoDB
MongoDB
 
Eurosentiment - Developing a new service
Eurosentiment - Developing a new serviceEurosentiment - Developing a new service
Eurosentiment - Developing a new service
mario_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 Development
P3 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 Programs
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit TestingPython Programming Essentials - M39 - Unit Testing
Python Programming Essentials - M39 - Unit Testing
P3 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 Concepts
P3 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 & Generators
P3 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 Comprehensions
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8Python Programming Essentials - M31 - PEP 8
Python Programming Essentials - M31 - PEP 8
P3 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 Files
P3 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 pdb
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging modulePython Programming Essentials - M27 - Logging module
Python Programming Essentials - M27 - Logging module
P3 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 modules
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math modulePython Programming Essentials - M24 - math module
Python Programming Essentials - M24 - math module
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime modulePython Programming Essentials - M23 - datetime module
Python Programming Essentials - M23 - datetime module
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File OperationsPython Programming Essentials - M22 - File Operations
Python Programming Essentials - M22 - File Operations
P3 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 Handling
P3 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 Objects
P3 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 Packages
P3 InfoTech Solutions Pvt. Ltd.
 
Python Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - FunctionsPython Programming Essentials - M17 - Functions
Python Programming Essentials - M17 - Functions
P3 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 Loops
P3 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

Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
saastr
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
Alex Pruden
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
Javier Junquera
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
DanBrown980551
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
Fwdays
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
DanBrown980551
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
Tatiana Kojar
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
Jason Packer
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
operationspcvita
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
Jason Yip
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
ssuserfac0301
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
saastr
 

Recently uploaded (20)

Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
Overcoming the PLG Trap: Lessons from Canva's Head of Sales & Head of EMEA Da...
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
zkStudyClub - LatticeFold: A Lattice-based Folding Scheme and its Application...
 
Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)GNSS spoofing via SDR (Criptored Talks 2024)
GNSS spoofing via SDR (Criptored Talks 2024)
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides5th LF Energy Power Grid Model Meet-up Slides
5th LF Energy Power Grid Model Meet-up Slides
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
"Scaling RAG Applications to serve millions of users",  Kevin Goedecke"Scaling RAG Applications to serve millions of users",  Kevin Goedecke
"Scaling RAG Applications to serve millions of users", Kevin Goedecke
 
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
LF Energy Webinar: Carbon Data Specifications: Mechanisms to Improve Data Acc...
 
Skybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoptionSkybuffer SAM4U tool for SAP license adoption
Skybuffer SAM4U tool for SAP license adoption
 
Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024Columbus Data & Analytics Wednesdays - June 2024
Columbus Data & Analytics Wednesdays - June 2024
 
The Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptxThe Microsoft 365 Migration Tutorial For Beginner.pptx
The Microsoft 365 Migration Tutorial For Beginner.pptx
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
[OReilly Superstream] Occupy the Space: A grassroots guide to engineering (an...
 
Taking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdfTaking AI to the Next Level in Manufacturing.pdf
Taking AI to the Next Level in Manufacturing.pdf
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
9 CEO's who hit $100m ARR Share Their Top Growth Tactics Nathan Latka, Founde...
 

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