KEMBAR78
Dictionaries in Python programming language | PPTX
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

Dictionaries in Python programming language

  • 1.
  • 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 • Createdusing 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 tocreate 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 • Usingsquare 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 toremove 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 containother 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: MemoryUsage • Higher memory usage than lists • Each key-value pair stores: • Hash of the key • Key itself • Value • Additional metadata
  • 14.
    Slide 13: BestPractices • Use meaningful keys • Check for key existence before access • Use get() with default values • Consider using collections.defaultdict • Keep keys immutable
  • 15.
    Slide 14: CommonPitfalls # 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 TypesFrom 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 • Dynamicviews 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 withDictionaries 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 withdictionary 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 • Createa 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: