SlideShare a Scribd company logo
Dictionaries in Python
What are Dictionaries?
• Key-value pair data structures
• Unordered, mutable, and dynamic
• Also known as associative arrays or hash maps in other languages
Dictionary Basics
• Created using curly braces {}
• Each item has a key and value, separated by colon :
• Keys must be unique and immutable
student = {
"name": "John Smith",
"age": 20,
"major": "Computer Science"
}
Multiple ways to create dictionaries
# Empty dictionary
dict1 = {}
dict2 = dict()
# Using dict() constructor
dict3 = dict(name="John", age=20)
# From list of tuples
pairs = [("apple", 1), ("banana", 2)]
dict4 = dict(pairs)
Accessing Values
• Using square bracket notation [ ]
• Using get() method (safer)
student = {"name": "John", "age": 20}
# Using brackets
print(student["name"]) # Output: John
# Using get()
print(student.get("age")) # Output: 20
print(student.get("grade", "N/A")) # Default value if key doesn't exist
Modifying Dictionaries
student = {"name": "John", "age": 20}
# Adding new key-value pair
student["grade"] = "A"
# Updating existing value
student["age"] = 21
# Updating multiple values
student.update({"age": 22, "major": "Physics"})
Several methods to remove items
student = {"name": "John", "age": 20, "grade": "A"}
# Remove specific key
del student["grade"]
# Pop item with specified key
student[“score”] = student.pop("grade")
# Remove and return last item
last_item = student.popitem()
# Clear all items
student.clear()
Common dictionary methods
• keys() - Returns list of all keys
• values() - Returns list of all values
• items() - Returns list of key-value pairs
student = {"name": "John", "age": 20}
print(student.keys())
print(student.values())
print(student.items())
Creating dictionaries using
comprehension
# Square numbers
squares = {x: x**2 for x in range(5)}
# Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Filtering with conditions
even_squares = {x: x**2 for x in range(5) if x % 2 == 0}
# Result: {0: 0, 2: 4, 4: 16}
Dictionaries can contain other
dictionaries
students = {
"John": {
"age": 20,
"grades": {"math": "A", "physics": "B"}
},
"Mary": {
"age": 19,
"grades": {"math": "B", "physics": "A"}
}
}
Common Use Cases
• Search
• Counting occurrences
• Configuration settings
• Caching results
• Graph representations
• JSON-like data structures
Dictionary Performance
• O(1) average case for insertions, deletions, and lookups
• Hash table implementation
• Comparison with lists:
• Lists: O(n) for search
• Dictionaries: O(1) for search
Slide 12: Memory Usage
• Higher memory usage than lists
• Each key-value pair stores:
• Hash of the key
• Key itself
• Value
• Additional metadata
Slide 13: Best Practices
• Use meaningful keys
• Check for key existence before access
• Use get() with default values
• Consider using collections.defaultdict
• Keep keys immutable
Slide 14: Common Pitfalls
# Mutable keys (will raise TypeError)
bad_dict = {[1, 2]: "value"} # Error!
# Key doesn't exist
student["grade"] # KeyError if 'grade' doesn't exist
# Modifying while iterating
for key in d: d[key+1] = 0 # Bad practice!
Special Dictionary Types From
collections
from collections import defaultdict, OrderedDict, Counter
# defaultdict - provides default values
d = defaultdict(list)
d["new_key"].append(1) # No KeyError!
# OrderedDict - maintains insertion order (pre-Python 3.7)
od = OrderedDict()
# Counter - counts occurrences
c = Counter(['a', 'b', 'a', 'c', 'a'])
Dictionary Views
• Dynamic views of dictionary entries
d = {"a": 1, "b": 2}
keys = d.keys()
values = d.values()
items = d.items()
# Views update automatically
d["c"] = 3
print(keys) # dict_keys(['a', 'b', 'c'])
Type Hints with Dictionaries
from typing import Dict, List, Union
# Simple dictionary
grades: Dict[str, float] = {"math": 95.5, "physics": 89.0}
# Complex dictionary
student: Dict[str, Union[str, int, List[str]]] = {
"name": "John",
"age": 20,
"courses": ["math", "physics"]
}
Set-like operations with dictionary
views
d1 = {"a": 1, "b": 2}
d2 = {"b": 3, "c": 4}
# Keys operations
keys1 = d1.keys()
keys2 = d2.keys()
# Union, intersection, difference
print(keys1 | keys2) # Union
print(keys1 & keys2) # Intersection
print(keys1 - keys2) # Difference
Real-world Example
def word_frequency(text: str) -> Dict[str, int]:
"""Count word frequencies in text."""
words = text.lower().split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
return frequency
text = "the quick brown fox jumps over the lazy dog"
print(word_frequency(text))
Practice Exercises
• Create a phone book dictionary
• Implement a cache using dictionary
• Count character frequencies in a string
• Create a nested dictionary for a school database
• Implement a simple graph using dictionary
• Python Documentation
• Real Python Tutorials
• Python Cookbook

More Related Content

PPTX
Basics of Python programming (part 2)
PDF
Python dictionaries
PDF
Programming in python Unit-1 Part-1
PPTX
Ggplot2 v3
PPTX
Farhana shaikh webinar_dictionaries
PPTX
Python programming –part 7
PDF
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
PDF
Dynamic languages, for software craftmanship group
Basics of Python programming (part 2)
Python dictionaries
Programming in python Unit-1 Part-1
Ggplot2 v3
Farhana shaikh webinar_dictionaries
Python programming –part 7
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
Dynamic languages, for software craftmanship group

Similar to Dictionaries in Python programming language (20)

PPTX
Python crush course
PPTX
python advanced data structure dictionary with examples python advanced data ...
PPTX
dictionary14 ppt FINAL.pptx
PPTX
Dictionaries in python
PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
PPT
2 UNIT CH3 Dictionaries v1.ppt
PPTX
Python - Data Structures
PPTX
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
PPT
Slides
PDF
An overview of Python 2.7
PDF
A tour of Python
PDF
First few months with Kotlin - Introduction through android examples
PDF
DevNation'15 - Using Lambda Expressions to Query a Datastore
PPTX
R language introduction
PDF
R language, an introduction
PPTX
Roslyn and C# 6.0 New Features
PPT
Dictionarys in python programming language.ppt
PDF
Introduction to Python
PDF
Kotlin Basics - Apalon Kotlin Sprint Part 2
PDF
Crystal presentation in NY
Python crush course
python advanced data structure dictionary with examples python advanced data ...
dictionary14 ppt FINAL.pptx
Dictionaries in python
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
2 UNIT CH3 Dictionaries v1.ppt
Python - Data Structures
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
Slides
An overview of Python 2.7
A tour of Python
First few months with Kotlin - Introduction through android examples
DevNation'15 - Using Lambda Expressions to Query a Datastore
R language introduction
R language, an introduction
Roslyn and C# 6.0 New Features
Dictionarys in python programming language.ppt
Introduction to Python
Kotlin Basics - Apalon Kotlin Sprint Part 2
Crystal presentation in NY
Ad

More from ssuserbad56d (11)

PPTX
Introduction to functions in C programming language
PPTX
OOP in Python Programming: Classes and Objects
PPTX
Software Testing and JUnit and Best Practices
PPT
search
PPT
search
PPT
Scaling Web Applications with Cassandra Presentation.ppt
PPT
Cassandra
PPT
PPTX
Covered Call
PDF
Lec04.pdf
PDF
Project.pdf
Introduction to functions in C programming language
OOP in Python Programming: Classes and Objects
Software Testing and JUnit and Best Practices
search
search
Scaling Web Applications with Cassandra Presentation.ppt
Cassandra
Covered Call
Lec04.pdf
Project.pdf
Ad

Recently uploaded (20)

PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
Insiders guide to clinical Medicine.pdf
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
PPTX
Introduction and Scope of Bichemistry.pptx
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
Module 3: Health Systems Tutorial Slides S2 2025
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
English Language Teaching from Post-.pdf
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Anesthesia in Laparoscopic Surgery in India
O5-L3 Freight Transport Ops (International) V1.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Renaissance Architecture: A Journey from Faith to Humanism
Insiders guide to clinical Medicine.pdf
Pharmacology of Heart Failure /Pharmacotherapy of CHF
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
Introduction and Scope of Bichemistry.pptx
Open folder Downloads.pdf yes yes ges yes
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PSYCHOLOGY IN EDUCATION.pdf ( nice pdf ...)
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Module 3: Health Systems Tutorial Slides S2 2025
NOI Hackathon - Summer Edition - GreenThumber.pptx
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Cardiovascular Pharmacology for pharmacy students.pptx
English Language Teaching from Post-.pdf

Dictionaries in Python programming language

  • 2. What are Dictionaries? • Key-value pair data structures • Unordered, mutable, and dynamic • Also known as associative arrays or hash maps in other languages
  • 3. Dictionary Basics • Created using curly braces {} • Each item has a key and value, separated by colon : • Keys must be unique and immutable student = { "name": "John Smith", "age": 20, "major": "Computer Science" }
  • 4. Multiple ways to create dictionaries # Empty dictionary dict1 = {} dict2 = dict() # Using dict() constructor dict3 = dict(name="John", age=20) # From list of tuples pairs = [("apple", 1), ("banana", 2)] dict4 = dict(pairs)
  • 5. Accessing Values • Using square bracket notation [ ] • Using get() method (safer) student = {"name": "John", "age": 20} # Using brackets print(student["name"]) # Output: John # Using get() print(student.get("age")) # Output: 20 print(student.get("grade", "N/A")) # Default value if key doesn't exist
  • 6. Modifying Dictionaries student = {"name": "John", "age": 20} # Adding new key-value pair student["grade"] = "A" # Updating existing value student["age"] = 21 # Updating multiple values student.update({"age": 22, "major": "Physics"})
  • 7. Several methods to remove items student = {"name": "John", "age": 20, "grade": "A"} # Remove specific key del student["grade"] # Pop item with specified key student[“score”] = student.pop("grade") # Remove and return last item last_item = student.popitem() # Clear all items student.clear()
  • 8. Common dictionary methods • keys() - Returns list of all keys • values() - Returns list of all values • items() - Returns list of key-value pairs student = {"name": "John", "age": 20} print(student.keys()) print(student.values()) print(student.items())
  • 9. Creating dictionaries using comprehension # Square numbers squares = {x: x**2 for x in range(5)} # Result: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} # Filtering with conditions even_squares = {x: x**2 for x in range(5) if x % 2 == 0} # Result: {0: 0, 2: 4, 4: 16}
  • 10. Dictionaries can contain other dictionaries students = { "John": { "age": 20, "grades": {"math": "A", "physics": "B"} }, "Mary": { "age": 19, "grades": {"math": "B", "physics": "A"} } }
  • 11. Common Use Cases • Search • Counting occurrences • Configuration settings • Caching results • Graph representations • JSON-like data structures
  • 12. Dictionary Performance • O(1) average case for insertions, deletions, and lookups • Hash table implementation • Comparison with lists: • Lists: O(n) for search • Dictionaries: O(1) for search
  • 13. Slide 12: Memory Usage • Higher memory usage than lists • Each key-value pair stores: • Hash of the key • Key itself • Value • Additional metadata
  • 14. Slide 13: Best Practices • Use meaningful keys • Check for key existence before access • Use get() with default values • Consider using collections.defaultdict • Keep keys immutable
  • 15. Slide 14: Common Pitfalls # Mutable keys (will raise TypeError) bad_dict = {[1, 2]: "value"} # Error! # Key doesn't exist student["grade"] # KeyError if 'grade' doesn't exist # Modifying while iterating for key in d: d[key+1] = 0 # Bad practice!
  • 16. Special Dictionary Types From collections from collections import defaultdict, OrderedDict, Counter # defaultdict - provides default values d = defaultdict(list) d["new_key"].append(1) # No KeyError! # OrderedDict - maintains insertion order (pre-Python 3.7) od = OrderedDict() # Counter - counts occurrences c = Counter(['a', 'b', 'a', 'c', 'a'])
  • 17. Dictionary Views • Dynamic views of dictionary entries d = {"a": 1, "b": 2} keys = d.keys() values = d.values() items = d.items() # Views update automatically d["c"] = 3 print(keys) # dict_keys(['a', 'b', 'c'])
  • 18. Type Hints with Dictionaries from typing import Dict, List, Union # Simple dictionary grades: Dict[str, float] = {"math": 95.5, "physics": 89.0} # Complex dictionary student: Dict[str, Union[str, int, List[str]]] = { "name": "John", "age": 20, "courses": ["math", "physics"] }
  • 19. Set-like operations with dictionary views d1 = {"a": 1, "b": 2} d2 = {"b": 3, "c": 4} # Keys operations keys1 = d1.keys() keys2 = d2.keys() # Union, intersection, difference print(keys1 | keys2) # Union print(keys1 & keys2) # Intersection print(keys1 - keys2) # Difference
  • 20. Real-world Example def word_frequency(text: str) -> Dict[str, int]: """Count word frequencies in text.""" words = text.lower().split() frequency = {} for word in words: frequency[word] = frequency.get(word, 0) + 1 return frequency text = "the quick brown fox jumps over the lazy dog" print(word_frequency(text))
  • 21. Practice Exercises • Create a phone book dictionary • Implement a cache using dictionary • Count character frequencies in a string • Create a nested dictionary for a school database • Implement a simple graph using dictionary • Python Documentation • Real Python Tutorials • Python Cookbook

Editor's Notes

  • #21: Additional Resources: