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

Similar to Dictionaries in Python programming language (20)

PPTX
Python dictionary
eman lotfy
 
PPTX
Dictionaries and Sets
Munazza-Mah-Jabeen
 
PPTX
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
PPTX
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
PPTX
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
PPTX
DICTIONARIES (1).pptx
KalashJain27
 
PPTX
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
PPTX
Chapter 16 Dictionaries
Praveen M Jigajinni
 
PDF
Dictionaries in Python programming for btech students
chandinignits
 
PPTX
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
examcelldavrng
 
PPTX
Dictionary in python
vikram mahendra
 
PPTX
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
PPTX
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
PDF
Python dictionary : past, present, future
delimitry
 
PPT
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
PPTX
Dictionary.pptx
RishuVerma34
 
PDF
Programming in python Unit-1 Part-1
Vikram Nandini
 
PPTX
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 
Python dictionary
eman lotfy
 
Dictionaries and Sets
Munazza-Mah-Jabeen
 
Dictionary in python Dictionary in python Dictionary in pDictionary in python...
sumanthcmcse
 
Ch 7 Dictionaries 1.pptx
KanchanaRSVVV
 
Ch_13_Dictionary.pptx
HarishParthasarathy4
 
DICTIONARIES (1).pptx
KalashJain27
 
Farhana shaikh webinar_dictionaries
Farhana Shaikh
 
Chapter 16 Dictionaries
Praveen M Jigajinni
 
Dictionaries in Python programming for btech students
chandinignits
 
DICTIONARIES TUTORIALS FOR ADVANCED LEARNING OF YTHON PROGRAMMING
examcelldavrng
 
Dictionary in python
vikram mahendra
 
dictionary14 ppt FINAL.pptx
MamtaKaundal1
 
Session10_Dictionaries.ppggyyyyyyyyyggggggggtx
pawankamal3
 
Python dictionary : past, present, future
delimitry
 
2 UNIT CH3 Dictionaries v1.ppt
tocidfh
 
Dictionary.pptx
RishuVerma34
 
Programming in python Unit-1 Part-1
Vikram Nandini
 
Python-Dictionaries.pptx easy way to learn dictionaries
panchalneha692
 

More from ssuserbad56d (11)

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

Recently uploaded (20)

PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
PDF
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PDF
Council of Chalcedon Re-Examined
Smiling Lungs
 
PPTX
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PDF
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
PPTX
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
PPTX
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
PDF
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
PPTX
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
PPT
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
PDF
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
epi editorial commitee meeting presentation
MIPLM
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
EDUCATIONAL MEDIA/ TEACHING AUDIO VISUAL AIDS
Sonali Gupta
 
The History of Phone Numbers in Stoke Newington by Billy Thomas
History of Stoke Newington
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
Council of Chalcedon Re-Examined
Smiling Lungs
 
Light Reflection and Refraction- Activities - Class X Science
SONU ACADEMY
 
Difference between write and update in odoo 18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
Chapter-V-DED-Entrepreneurship: Institutions Facilitating Entrepreneurship
Dayanand Huded
 
Universal immunization Programme (UIP).pptx
Vishal Chanalia
 
care of patient with elimination needs.pptx
Rekhanjali Gupta
 
Vani - The Voice of Excellence - Jul 2025 issue
Savipriya Raghavendra
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
How to Send Email From Odoo 18 Website - Odoo Slides
Celine George
 
Indian Contract Act 1872, Business Law #MBA #BBA #BCOM
priyasinghy107
 
Women's Health: Essential Tips for Every Stage.pdf
Iftikhar Ahmed
 
Ad

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: