SlideShare a Scribd company logo
DICTIONARIES
IN PYTHON
What is Dictionary
 It is another collection in Python but with different in way of
storing and accessing. Other collection like list, tuple, string are
having an index associated with every element but Python
Dictionary have a “key” associated with every element. That’s
why pythondictionaries are knownasKEY:VALUEpairs.
 Like with English dictionary we search any word for meaning
associated with it, similarly in Python we search for “key” to get
itsassociatedvalue rather thansearching for an index.
Creating a Dictionary
Syntaxto create dictionary:
dictionary_name= {key1:value,key2:value,….} Example
>>> emp= {"empno":1,"name":"Shahrukh","fee":1500000}
Here Keysare :“empno”,“name” and “fee” Valuesare: 1,
“Shahrukh”,1500000
Note:
1) Dictionary elementsmustbe betweencurlybrackets
2
) Eachvaluemustbe paired withkey element
3
) Eachkey-valuepair mustbe separated by comma(,)
Creating a dictionary
 Dict1 = {} # emptydictionary
 DaysInMonth={"Jan":31,"Feb":28,"Mar":31,"Apr":31
"May":31,"Jun":30,"Jul":31,"Aug":31
"Sep":30,"Oct":31,"Nov":30,"Dec":31}
Note:Keysof dictionary mustof immutabletype suchas:
- Apython string
- A number
- Atuple(containingonly immutable entries)
- If wetry to give mutable type askey,python will give an error
- >>>dict2 = {[2,3]:”abc”} #Error
Accessingelementsof Dictionary
 Toaccess Dictionary elementsweneedthe “key”
>>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>> mydict['salary']
25000
Note: if youtry to access“key” whichisnot in the dictionary, python
will raise an error
>>>mydict[‘comm’] #Error
Traversing a Dictionary
 Pythonallows to apply “for” loop to traverse every
elementof dictionary based ontheir “key”. Forloop
will get every key of dictionary and wecanaccess
every elementbased ontheir key.
mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
for key in mydict:
print(key,'=',mydict[key])
Accessingkeysand valuessimultaneously
>>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000}
>>>mydict.keys()
dict_keys(['empno','name', 'dept', 'salary'])
>>>mydict.values()
dict_values([1,'Shivam', 'sales', 25000])
Wecan convertthesequence returnedby keys() and values() by using list() as shown below:
>>> list(mydict.keys()) ['empno', 'name',
'dept', 'salary']
>>> list(mydict.values()) [1,
'Shivam', 'sales', 25000]
Characteristics of a Dictionary
 Unordered set
Adictionary isa unorderedsetof key:valuepair
 Not a sequence
Unlike a string, tuple, and list, a dictionary is not a sequence because it is
unordered set of elements. The sequences are indexed by a range of
ordinal numbers.Hencethey are ordered but a dictionary is an unordered
collection
 Indexed by Keys,Not Numbers
Dictionaries are indexed by keys.Keysare immutable type
Characteristicsof a Dictionary
 Keysmustbeunique
Eachkeywithindictionary mustbe unique.Howevertwo uniquekeyscanhavesamevalues.
>>> data={1:100, 2:200,3:300,4:200}
 Mutable
Likelists,dictionary are alsomutable.We canchangethevalue of a certain “key” in place
Data[3]=400
>>>Data
So,to changevalueof dictionary theformat is :
◼ DictionaryName[“key” / key]=new_value
Youcannotonlychangebut youcanadd newkey:valuepair:
Working with Dictionaries
 Multiple ways of creating dictionaries
1. Initializing a Dictionary : in this method all the key:value pairs of
dictionary are written collectively separated by commasand enclosed in
curly braces Student={“roll”:1,”name”:”Scott”,”Per”:90}
2. Adding key:value pair to an empty Dictionary :in this method we first
create empty dictionary and then key:value pair are added to it one
pair at a time For example
#Empty dictionary
Alphabets={}
Or
Alphabets = dict()
Working with Dictionaries
 Multiple ways of creating dictionaries
Nowwewill add newpair to thisemptydictionary oneby one as:
Alphabets = {}
Alphabets[“a”]=“apple”
Alphabets[“b”]=“boy”
Adding elementsto Dictionary
 Youcanadd newelementto dictionary as:
dictionaryName[“key”]= value
 T
oprint elementsof nesteddictionary isas :
>>> Visitor=
{'Name':'Scott','Address':{'hno':'11A/B','City':'Kanpur','PinCode'
:'208004'}}
>>> Visitor
{'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode':
'2080
04'}}
>>> Visitor['Name'] 'Scott'
Updating elementsin Dictionary
 Dictionaryname[“key”]=value
>>> data={1:100, 2:200,3:300,4:200}
>>> data[3]=1500
>>> data[3] # 1500
Deleting elementsfrom Dictionary
del dictionaryName[“Key”]
>>> D1 = {1:10,2:20,3:30,4:40}
>>> delD1[2]
>>> D1
1:10,3:20,4:40
• If you trytoremovetheitemwhose key does not
exists, thepython runtimeerror occurs.
• Del D1[5] #Error
pop() elementsfrom Dictionary
dictionaryName.pop([“Key”])
>>> D1 = {1:10,2:20,3:30,4:40}
>>> D1.pop(2)
1:10,3:20,4:40
Note:ifkeypassedtopop()doesn’texiststhenpython
willraiseanexception.
Pop()functionallowsustocustomizedtheerror
messagedisplayedbyuseofwrongkey
pop() elementsfrom Dictionary
>>> d1
{'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'}
>>>d1.pop(‘a’)
>>> d1.pop(‘d‘,’Notfound’)
Not found
Dictionary part 1
Dictionary part 1

More Related Content

What's hot (18)

PPTX
Chap 3php array part1
monikadeshmane
 
PDF
PHP Unit 4 arrays
Kumar
 
PDF
How I Learned to Stop Worrying and Love Email::: The 2007 PEP Talk!!
Ricardo Signes
 
PPTX
Marcs (bio)perl course
BITS
 
PPT
Php array
Core Lee
 
PPTX
Array in php
Ashok Kumar
 
PDF
4.1 PHP Arrays
Jalpesh Vasa
 
PPT
Web Technology - PHP Arrays
Tarang Desai
 
PDF
DBIx::Class introduction - 2010
leo lapworth
 
PDF
Collections
SV.CO
 
PPTX
.net F# mutable dictionay
DrRajeshreeKhande
 
PPTX
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
PDF
Scripting3
Nao Dara
 
PPTX
DTD elements
preetikapri1
 
PDF
DBIx::Class beginners
leo lapworth
 
PPT
Php Using Arrays
mussawir20
 
PDF
Php array
Nikul Shah
 
Chap 3php array part1
monikadeshmane
 
PHP Unit 4 arrays
Kumar
 
How I Learned to Stop Worrying and Love Email::: The 2007 PEP Talk!!
Ricardo Signes
 
Marcs (bio)perl course
BITS
 
Php array
Core Lee
 
Array in php
Ashok Kumar
 
4.1 PHP Arrays
Jalpesh Vasa
 
Web Technology - PHP Arrays
Tarang Desai
 
DBIx::Class introduction - 2010
leo lapworth
 
Collections
SV.CO
 
.net F# mutable dictionay
DrRajeshreeKhande
 
ITS-16163: Module 5 Using Lists and Dictionaries
oudesign
 
Scripting3
Nao Dara
 
DTD elements
preetikapri1
 
DBIx::Class beginners
leo lapworth
 
Php Using Arrays
mussawir20
 
Php array
Nikul Shah
 

Similar to Dictionary part 1 (20)

PPTX
DICTIONARIES (1).pptx
KalashJain27
 
PDF
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
PPTX
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
PPTX
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
PPTX
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
cjrfailure
 
PPTX
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
PPTX
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
PPTX
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
PDF
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
ZainabHaneen
 
PPTX
Operations-of-Strings-Lists-Tuples-and-Dictionaries-in-Python (1).pptx
AyushArvind1
 
PDF
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
PPTX
Collections123456789009876543211234567.pptx
arghya0001
 
PPTX
Dictionaries and Sets
Munazza-Mah-Jabeen
 
PDF
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 
PPTX
Dictionary.pptx
RishuVerma34
 
PPTX
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
PPTX
Operations-of-Strings-Lists-Tuples-and-Dictionaries-in-Python.pptx
AyushArvind1
 
PPTX
dataStructuresInPython.pptx
YashaswiniChandrappa1
 
PPTX
Unit 1(Lesson7).pptx
NiteshKumar862859
 
DICTIONARIES (1).pptx
KalashJain27
 
CHAPTER- 9 PYTHON DICTIONARIES.pdf computer science
Bavish5
 
PYTHON Data structures Fundamentals: DICTIONARIES
KanadamKarteekaPavan1
 
Python Fundamental Data structures: Dictionaries
KanadamKarteekaPavan1
 
Dictionariesasdfghjsdfghjklsdfghjkl.pptx
cjrfailure
 
Python Dynamic Data type List & Dictionaries
RuchiNagar3
 
Chapter 14 Dictionary.pptx
jchandrasekhar3
 
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
"Python Dictionary: The Key to Efficient Data Storage, Manipulation, and Vers...
ZainabHaneen
 
Operations-of-Strings-Lists-Tuples-and-Dictionaries-in-Python (1).pptx
AyushArvind1
 
ESIT135 Problem Solving Using Python Notes of Unit-3
prasadmutkule1
 
Collections123456789009876543211234567.pptx
arghya0001
 
Dictionaries and Sets
Munazza-Mah-Jabeen
 
Python-Ukllllllllllllllllllllllllllllnit 2.pdklllllllf
Meha46
 
Dictionary.pptx
RishuVerma34
 
An Introduction to Tuple List Dictionary in Python
yashar Aliabasi
 
Operations-of-Strings-Lists-Tuples-and-Dictionaries-in-Python.pptx
AyushArvind1
 
dataStructuresInPython.pptx
YashaswiniChandrappa1
 
Unit 1(Lesson7).pptx
NiteshKumar862859
 
Ad

Recently uploaded (20)

PPT
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
PDF
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
PPTX
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
PDF
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
PPTX
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
PPTX
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
PPTX
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
PPTX
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
PPTX
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
PPTX
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
PPTX
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
DOCX
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
PPTX
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
DOCX
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
PDF
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
PPTX
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
PDF
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
PPTX
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
PPTX
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
PPTX
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
DRUGS USED IN THERAPY OF SHOCK, Shock Therapy, Treatment or management of shock
Rajshri Ghogare
 
EXCRETION-STRUCTURE OF NEPHRON,URINE FORMATION
raviralanaresh2
 
I INCLUDED THIS TOPIC IS INTELLIGENCE DEFINITION, MEANING, INDIVIDUAL DIFFERE...
parmarjuli1412
 
The-Invisible-Living-World-Beyond-Our-Naked-Eye chapter 2.pdf/8th science cur...
Sandeep Swamy
 
Command Palatte in Odoo 18.1 Spreadsheet - Odoo Slides
Celine George
 
Python-Application-in-Drug-Design by R D Jawarkar.pptx
Rahul Jawarkar
 
INTESTINALPARASITES OR WORM INFESTATIONS.pptx
PRADEEP ABOTHU
 
ENGLISH 8 WEEK 3 Q1 - Analyzing the linguistic, historical, andor biographica...
OliverOllet
 
Translation_ Definition, Scope & Historical Development.pptx
DhatriParmar
 
The Future of Artificial Intelligence Opportunities and Risks Ahead
vaghelajayendra784
 
Cybersecurity: How to Protect your Digital World from Hackers
vaidikpanda4
 
pgdei-UNIT -V Neurological Disorders & developmental disabilities
JELLA VISHNU DURGA PRASAD
 
Unlock the Power of Cursor AI: MuleSoft Integrations
Veera Pallapu
 
Modul Ajar Deep Learning Bahasa Inggris Kelas 11 Terbaru 2025
wahyurestu63
 
TOP 10 AI TOOLS YOU MUST LEARN TO SURVIVE IN 2025 AND ABOVE
digilearnings.com
 
Rules and Regulations of Madhya Pradesh Library Part-I
SantoshKumarKori2
 
Antianginal agents, Definition, Classification, MOA.pdf
Prerana Jadhav
 
Dakar Framework Education For All- 2000(Act)
santoshmohalik1
 
Cleaning Validation Ppt Pharmaceutical validation
Ms. Ashatai Patil
 
Electrophysiology_of_Heart. Electrophysiology studies in Cardiovascular syste...
Rajshri Ghogare
 
Ad

Dictionary part 1

  • 2. What is Dictionary  It is another collection in Python but with different in way of storing and accessing. Other collection like list, tuple, string are having an index associated with every element but Python Dictionary have a “key” associated with every element. That’s why pythondictionaries are knownasKEY:VALUEpairs.  Like with English dictionary we search any word for meaning associated with it, similarly in Python we search for “key” to get itsassociatedvalue rather thansearching for an index.
  • 3. Creating a Dictionary Syntaxto create dictionary: dictionary_name= {key1:value,key2:value,….} Example >>> emp= {"empno":1,"name":"Shahrukh","fee":1500000} Here Keysare :“empno”,“name” and “fee” Valuesare: 1, “Shahrukh”,1500000 Note: 1) Dictionary elementsmustbe betweencurlybrackets 2 ) Eachvaluemustbe paired withkey element 3 ) Eachkey-valuepair mustbe separated by comma(,)
  • 4. Creating a dictionary  Dict1 = {} # emptydictionary  DaysInMonth={"Jan":31,"Feb":28,"Mar":31,"Apr":31 "May":31,"Jun":30,"Jul":31,"Aug":31 "Sep":30,"Oct":31,"Nov":30,"Dec":31} Note:Keysof dictionary mustof immutabletype suchas: - Apython string - A number - Atuple(containingonly immutable entries) - If wetry to give mutable type askey,python will give an error - >>>dict2 = {[2,3]:”abc”} #Error
  • 5. Accessingelementsof Dictionary  Toaccess Dictionary elementsweneedthe “key” >>>mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} >>> mydict['salary'] 25000 Note: if youtry to access“key” whichisnot in the dictionary, python will raise an error >>>mydict[‘comm’] #Error
  • 6. Traversing a Dictionary  Pythonallows to apply “for” loop to traverse every elementof dictionary based ontheir “key”. Forloop will get every key of dictionary and wecanaccess every elementbased ontheir key. mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} for key in mydict: print(key,'=',mydict[key])
  • 7. Accessingkeysand valuessimultaneously >>> mydict={'empno':1,'name':'Shivam','dept':'sales','salary':25000} >>>mydict.keys() dict_keys(['empno','name', 'dept', 'salary']) >>>mydict.values() dict_values([1,'Shivam', 'sales', 25000]) Wecan convertthesequence returnedby keys() and values() by using list() as shown below: >>> list(mydict.keys()) ['empno', 'name', 'dept', 'salary'] >>> list(mydict.values()) [1, 'Shivam', 'sales', 25000]
  • 8. Characteristics of a Dictionary  Unordered set Adictionary isa unorderedsetof key:valuepair  Not a sequence Unlike a string, tuple, and list, a dictionary is not a sequence because it is unordered set of elements. The sequences are indexed by a range of ordinal numbers.Hencethey are ordered but a dictionary is an unordered collection  Indexed by Keys,Not Numbers Dictionaries are indexed by keys.Keysare immutable type
  • 9. Characteristicsof a Dictionary  Keysmustbeunique Eachkeywithindictionary mustbe unique.Howevertwo uniquekeyscanhavesamevalues. >>> data={1:100, 2:200,3:300,4:200}  Mutable Likelists,dictionary are alsomutable.We canchangethevalue of a certain “key” in place Data[3]=400 >>>Data So,to changevalueof dictionary theformat is : ◼ DictionaryName[“key” / key]=new_value Youcannotonlychangebut youcanadd newkey:valuepair:
  • 10. Working with Dictionaries  Multiple ways of creating dictionaries 1. Initializing a Dictionary : in this method all the key:value pairs of dictionary are written collectively separated by commasand enclosed in curly braces Student={“roll”:1,”name”:”Scott”,”Per”:90} 2. Adding key:value pair to an empty Dictionary :in this method we first create empty dictionary and then key:value pair are added to it one pair at a time For example #Empty dictionary Alphabets={} Or Alphabets = dict()
  • 11. Working with Dictionaries  Multiple ways of creating dictionaries Nowwewill add newpair to thisemptydictionary oneby one as: Alphabets = {} Alphabets[“a”]=“apple” Alphabets[“b”]=“boy”
  • 12. Adding elementsto Dictionary  Youcanadd newelementto dictionary as: dictionaryName[“key”]= value  T oprint elementsof nesteddictionary isas : >>> Visitor= {'Name':'Scott','Address':{'hno':'11A/B','City':'Kanpur','PinCode' :'208004'}} >>> Visitor {'Name': 'Scott', 'Address': {'hno': '11A/B', 'City': 'Kanpur', 'PinCode': '2080 04'}} >>> Visitor['Name'] 'Scott'
  • 13. Updating elementsin Dictionary  Dictionaryname[“key”]=value >>> data={1:100, 2:200,3:300,4:200} >>> data[3]=1500 >>> data[3] # 1500
  • 14. Deleting elementsfrom Dictionary del dictionaryName[“Key”] >>> D1 = {1:10,2:20,3:30,4:40} >>> delD1[2] >>> D1 1:10,3:20,4:40 • If you trytoremovetheitemwhose key does not exists, thepython runtimeerror occurs. • Del D1[5] #Error
  • 15. pop() elementsfrom Dictionary dictionaryName.pop([“Key”]) >>> D1 = {1:10,2:20,3:30,4:40} >>> D1.pop(2) 1:10,3:20,4:40 Note:ifkeypassedtopop()doesn’texiststhenpython willraiseanexception. Pop()functionallowsustocustomizedtheerror messagedisplayedbyuseofwrongkey
  • 16. pop() elementsfrom Dictionary >>> d1 {'a': 'apple', 'b': 'ball', 'c': 'caterpillar', 'd': 'dog'} >>>d1.pop(‘a’) >>> d1.pop(‘d‘,’Notfound’) Not found