SlideShare a Scribd company logo
1 of 11
Dictionaries in Python3
By Lakshmi Sarvani Videla
NOTE: all the contents in this ppt are taken from w3schools
https://www.w3schools.com/python/
Dictionary
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
The dict() Constructor
It is also possible to use the dict() constructor to make a dictionary:
Example
thisdict = dict(brand="Ford", model="Mustang", year=1964)
# note that keywords are not string literals
# note the use of equals rather than colon for the assignment
print(thisdict)
Accessing Items
You can access the items of a dictionary by
referring to its key name, inside square brackets:
Example
Get the value of the "model" key:
x = thisdict["model"]
There is also a method called get() that will give
you the same result:
Example
Get the value of the "model" key:
x = thisdict.get("model")
Change Values
You can change the value of a specific item by referring to its key name:
Example
Change the "year" to 2018:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
thisdict["year"] = 2018
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are the keys of the dictionary, but
there are methods to return the values as well.
Example
Print all key names in the dictionary, one by one:
for x in thisdict:
print(x)
Example
Print all values in the dictionary, one by one:
for x in thisdict:
print(thisdict[x])
You can also use the values() function to return values of a dictionary:
for x in thisdict.values():
print(x)
Check if Key Exists
To determine if a specified key is present in a dictionary use the in keyword:
Example
Check if "model" is present in the dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict dictionary")
Dictionary Length
To determine how many items (key-value pairs) a dictionary have, use the len() method.
Example
Print the number of items in the dictionary:
print(len(thisdict))
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Create a dictionary with 3 keys, all with the value 0:
x = ('key1', 'key2', 'key3')
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.pop("model")
print(thisdict)
The popitem() method removes the last inserted item (in versions before 3.7, a random item
is removed instead):
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
thisdict.popitem()
print(thisdict)
Example
The del keyword removes the item with the specified key name:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964}
del thisdict["model"]
print(thisdict)
Example
The clear() keyword empties the dictionary:
thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 }
thisdict.clear()
print(thisdict)
Copy the car dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.copy()
print(x)
Get the value of the "model" item:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.setdefault("model", "Bronco")
print(x)
Insert an item to the dictionary:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
car.update({"color": "White"})
print(car)
Return the dictionary's key-value pairs:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.items()
print(x)

More Related Content

What's hot

File handling in C++
File handling in C++File handling in C++
File handling in C++Hitesh Kumar
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Raj Naik
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams Ahmed Farag
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in pythonSantosh Verma
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Python functions
Python functionsPython functions
Python functionsAliyamanasa
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programmingPraveen M Jigajinni
 
Storage class in c
Storage class in cStorage class in c
Storage class in ckash95
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize outputSyed Zaid Irshad
 

What's hot (20)

Java Strings
Java StringsJava Strings
Java Strings
 
File handling in C++
File handling in C++File handling in C++
File handling in C++
 
Java Method, Static Block
Java Method, Static BlockJava Method, Static Block
Java Method, Static Block
 
Python list
Python listPython list
Python list
 
Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive Data Types - Premetive and Non Premetive
Data Types - Premetive and Non Premetive
 
C string
C stringC string
C string
 
C++ Files and Streams
C++ Files and Streams C++ Files and Streams
C++ Files and Streams
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Sets in python
Sets in pythonSets in python
Sets in python
 
Chapter 14 strings
Chapter 14 stringsChapter 14 strings
Chapter 14 strings
 
Functions in python
Functions in python Functions in python
Functions in python
 
Python functions
Python functionsPython functions
Python functions
 
Chapter 04 object oriented programming
Chapter 04 object oriented programmingChapter 04 object oriented programming
Chapter 04 object oriented programming
 
Storage class in c
Storage class in cStorage class in c
Storage class in c
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Using single row functions to customize output
Using single row functions to customize outputUsing single row functions to customize output
Using single row functions to customize output
 
Pointer to function 1
Pointer to function 1Pointer to function 1
Pointer to function 1
 
Python programming : Abstract classes interfaces
Python programming : Abstract classes interfacesPython programming : Abstract classes interfaces
Python programming : Abstract classes interfaces
 
Python :variable types
Python :variable typesPython :variable types
Python :variable types
 

Similar to Dictionary

w3schools.com THE WORLDS LARGEST WEB DEVELOPER SITE
w3schools.com  THE WORLDS LARGEST WEB DEVELOPER SITE w3schools.com  THE WORLDS LARGEST WEB DEVELOPER SITE
w3schools.com THE WORLDS LARGEST WEB DEVELOPER SITE tidwellerin392
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++TemplatesGanesh Samarthyam
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptxCruiseCH
 
Dictionary e book
Dictionary e bookDictionary e book
Dictionary e booksharmilakt
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.pptbalewayalew
 
MDE=Model Driven Everything (Spanish Eclipse Day 2009)
MDE=Model Driven Everything (Spanish Eclipse Day 2009)MDE=Model Driven Everything (Spanish Eclipse Day 2009)
MDE=Model Driven Everything (Spanish Eclipse Day 2009)Jordi Cabot
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data ModelingDATAVERSITY
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practicesTan Tran
 
Trabajo de power point
Trabajo de power pointTrabajo de power point
Trabajo de power pointDoris2012
 
MacAD.UK 2018: Your Code Should Document Itself
MacAD.UK 2018: Your Code Should Document ItselfMacAD.UK 2018: Your Code Should Document Itself
MacAD.UK 2018: Your Code Should Document ItselfBryson Tyrrell
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDBrogerbodamer
 
Code snippets
Code snippetsCode snippets
Code snippetsSireesh K
 

Similar to Dictionary (20)

w3schools.com THE WORLDS LARGEST WEB DEVELOPER SITE
w3schools.com  THE WORLDS LARGEST WEB DEVELOPER SITE w3schools.com  THE WORLDS LARGEST WEB DEVELOPER SITE
w3schools.com THE WORLDS LARGEST WEB DEVELOPER SITE
 
Python dictionary
Python dictionaryPython dictionary
Python dictionary
 
Seventh session
Seventh sessionSeventh session
Seventh session
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 
An Introduction To C++Templates
An Introduction To C++TemplatesAn Introduction To C++Templates
An Introduction To C++Templates
 
Google code search
Google code searchGoogle code search
Google code search
 
Week 10.pptx
Week 10.pptxWeek 10.pptx
Week 10.pptx
 
Dictionary e book
Dictionary e bookDictionary e book
Dictionary e book
 
PE1 Module 4.ppt
PE1 Module 4.pptPE1 Module 4.ppt
PE1 Module 4.ppt
 
MDE=Model Driven Everything (Spanish Eclipse Day 2009)
MDE=Model Driven Everything (Spanish Eclipse Day 2009)MDE=Model Driven Everything (Spanish Eclipse Day 2009)
MDE=Model Driven Everything (Spanish Eclipse Day 2009)
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling10gen Presents Schema Design and Data Modeling
10gen Presents Schema Design and Data Modeling
 
C# conventions & good practices
C# conventions & good practicesC# conventions & good practices
C# conventions & good practices
 
Python training for beginners
Python training for beginnersPython training for beginners
Python training for beginners
 
Trabajo de power point
Trabajo de power pointTrabajo de power point
Trabajo de power point
 
MacAD.UK 2018: Your Code Should Document Itself
MacAD.UK 2018: Your Code Should Document ItselfMacAD.UK 2018: Your Code Should Document Itself
MacAD.UK 2018: Your Code Should Document Itself
 
Schema Design with MongoDB
Schema Design with MongoDBSchema Design with MongoDB
Schema Design with MongoDB
 
Code snippets
Code snippetsCode snippets
Code snippets
 
Chapter 16 Dictionaries
Chapter 16 DictionariesChapter 16 Dictionaries
Chapter 16 Dictionaries
 
Language Search
Language SearchLanguage Search
Language Search
 

More from Lakshmi Sarvani Videla (20)

Data Science Using Python
Data Science Using PythonData Science Using Python
Data Science Using Python
 
Programs on multithreading
Programs on multithreadingPrograms on multithreading
Programs on multithreading
 
Menu Driven programs in Java
Menu Driven programs in JavaMenu Driven programs in Java
Menu Driven programs in Java
 
Recursion in C
Recursion in CRecursion in C
Recursion in C
 
Simple questions on structures concept
Simple questions on structures conceptSimple questions on structures concept
Simple questions on structures concept
 
Errors incompetitiveprogramming
Errors incompetitiveprogrammingErrors incompetitiveprogramming
Errors incompetitiveprogramming
 
Relational Operators in C
Relational Operators in CRelational Operators in C
Relational Operators in C
 
Recursive functions in C
Recursive functions in CRecursive functions in C
Recursive functions in C
 
Function Pointer in C
Function Pointer in CFunction Pointer in C
Function Pointer in C
 
Functions
FunctionsFunctions
Functions
 
Java sessionnotes
Java sessionnotesJava sessionnotes
Java sessionnotes
 
Singlelinked list
Singlelinked listSinglelinked list
Singlelinked list
 
Graphs
GraphsGraphs
Graphs
 
B trees
B treesB trees
B trees
 
Functions in python3
Functions in python3Functions in python3
Functions in python3
 
Sets
SetsSets
Sets
 
DataStructures notes
DataStructures notesDataStructures notes
DataStructures notes
 
Solutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structuresSolutionsfor co2 C Programs for data structures
Solutionsfor co2 C Programs for data structures
 
C programs
C programsC programs
C programs
 
Data Mining: Data Preprocessing
Data Mining: Data PreprocessingData Mining: Data Preprocessing
Data Mining: Data Preprocessing
 

Recently uploaded

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
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
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 

Recently uploaded (20)

SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
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
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 

Dictionary

  • 1. Dictionaries in Python3 By Lakshmi Sarvani Videla NOTE: all the contents in this ppt are taken from w3schools https://www.w3schools.com/python/
  • 2. Dictionary A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values. Example Create and print a dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } print(thisdict) The dict() Constructor It is also possible to use the dict() constructor to make a dictionary: Example thisdict = dict(brand="Ford", model="Mustang", year=1964) # note that keywords are not string literals # note the use of equals rather than colon for the assignment print(thisdict)
  • 3. Accessing Items You can access the items of a dictionary by referring to its key name, inside square brackets: Example Get the value of the "model" key: x = thisdict["model"] There is also a method called get() that will give you the same result: Example Get the value of the "model" key: x = thisdict.get("model")
  • 4. Change Values You can change the value of a specific item by referring to its key name: Example Change the "year" to 2018: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["year"] = 2018
  • 5. Loop Through a Dictionary You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. Example Print all key names in the dictionary, one by one: for x in thisdict: print(x) Example Print all values in the dictionary, one by one: for x in thisdict: print(thisdict[x]) You can also use the values() function to return values of a dictionary: for x in thisdict.values(): print(x)
  • 6. Check if Key Exists To determine if a specified key is present in a dictionary use the in keyword: Example Check if "model" is present in the dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } if "model" in thisdict: print("Yes, 'model' is one of the keys in the thisdict dictionary") Dictionary Length To determine how many items (key-value pairs) a dictionary have, use the len() method. Example Print the number of items in the dictionary: print(len(thisdict))
  • 7. Adding Items Adding an item to the dictionary is done by using a new index key and assigning a value to it: Example thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict["color"] = "red" print(thisdict) Create a dictionary with 3 keys, all with the value 0: x = ('key1', 'key2', 'key3') y = 0 thisdict = dict.fromkeys(x, y) print(thisdict)
  • 8. Removing Items There are several methods to remove items from a dictionary: Example The pop() method removes the item with the specified key name: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} thisdict.pop("model") print(thisdict) The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead): thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} thisdict.popitem() print(thisdict) Example The del keyword removes the item with the specified key name: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} del thisdict["model"] print(thisdict)
  • 9. Example The clear() keyword empties the dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } thisdict.clear() print(thisdict) Copy the car dictionary: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.copy() print(x)
  • 10. Get the value of the "model" item: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.setdefault("model", "Bronco") print(x) Insert an item to the dictionary: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.update({"color": "White"}) print(car)
  • 11. Return the dictionary's key-value pairs: car = { "brand": "Ford", "model": "Mustang", "year": 1964 } x = car.items() print(x)