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
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'])
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