Python Dictionaries

Python dictionaries are mutable data structures that store data in key-value pairs. Each key in a Python dictionary must be unique and immutable (strings, numbers, or tuples), while values can be of any data type. Python dictionaries are also known as associative arrays or hash maps in other programming languages.

# Simple dictionary example
student_grades = {"Alice": 95, "Bob": 87, "Charlie": 92}

Creating Python Dictionaries

There are several ways to create Python dictionaries. Let’s explore each method with detailed explanations.

Using Curly Braces

The most common way to create Python dictionaries is using curly braces {}. This method allows you to define key-value pairs directly.

# Empty dictionary
empty_dict = {}

# Dictionary with initial values
colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}

Using the dict() Constructor

The dict() constructor provides another way to create Python dictionaries. This method is particularly useful when creating dictionaries from other data structures.

# Using dict() with keyword arguments
person = dict(name="John", age=30, city="New York")

# Using dict() with a list of tuples
coordinates = dict([("x", 10), ("y", 20), ("z", 30)])

Using Dictionary Comprehension

Dictionary comprehension is a concise way to create Python dictionaries using a single line of code. This method is powerful for generating dictionaries based on existing iterables.

# Creating a dictionary of squares
squares = {x: x**2 for x in range(1, 6)}
# Result: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Accessing Dictionary Elements

Python dictionaries provide multiple ways to access stored values. Understanding these access methods is essential for working with dictionary data effectively.

Using Square Brackets

The most direct way to access dictionary values is using square brackets with the key name.

student_info = {"name": "Sarah", "grade": 88, "subject": "Mathematics"}
print(student_info["name"]) # Output: Sarah

Using the get() Method

The get() method provides a safer way to access dictionary values, as it returns None or a default value if the key doesn’t exist.

product = {"name": "Laptop", "price": 999.99}
print(product.get("name")) # Output: Laptop
print(product.get("discount", "No discount")) # Output: No discount

Modifying Python Dictionaries

Python dictionaries are mutable, which means you can modify their contents after creation. Let’s explore different ways to modify dictionary data.

Adding New Key-Value Pairs

You can add new elements to Python dictionaries using square bracket notation or the update() method.

inventory = {"apples": 50, "bananas": 30}
inventory["oranges"] = 25 # Adding a new item
print(inventory) # Output: {"apples": 50, "bananas": 30, "oranges": 25}

Updating Existing Values

Modifying existing values in Python dictionaries is straightforward using the assignment operator.

scores = {"player1": 100, "player2": 85}
scores["player1"] = 120 # Updating existing value
print(scores) # Output: {"player1": 120, "player2": 85}

Using the update() Method

The update() method allows you to add multiple key-value pairs or merge dictionaries.

base_config = {"host": "localhost", "port": 8080}
additional_config = {"timeout": 30, "retries": 3}
base_config.update(additional_config)
print(base_config) # Output: {"host": "localhost", "port": 8080, "timeout": 30, "retries": 3}

Dictionary Methods and Operations

Python dictionaries come with numerous built-in methods that make data manipulation easier and more efficient.

keys() Method

The keys() method returns a view object containing all dictionary keys.

menu = {"pizza": 12.99, "burger": 8.99, "salad": 6.99}
menu_items = menu.keys()
print(list(menu_items)) # Output: ['pizza', 'burger', 'salad']

values() Method

The values() method returns a view object containing all dictionary values.

temperatures = {"Monday": 25, "Tuesday": 28, "Wednesday": 22}
temp_values = temperatures.values()
print(list(temp_values)) # Output: [25, 28, 22]

items() Method

The items() method returns a view object containing key-value pairs as tuples.

countries = {"USA": "Washington", "France": "Paris", "Japan": "Tokyo"}
country_items = countries.items()
print(list(country_items)) # Output: [('USA', 'Washington'), ('France', 'Paris'), ('Japan', 'Tokyo')]

pop() Method

The pop() method removes and returns the value for a specified key.

shopping_cart = {"laptop": 999, "mouse": 25, "keyboard": 75}
removed_item = shopping_cart.pop("mouse")
print(removed_item) # Output: 25
print(shopping_cart) # Output: {"laptop": 999, "keyboard": 75}

popitem() Method

The popitem() method removes and returns the last inserted key-value pair.

recent_orders = {"order1": "pending", "order2": "shipped", "order3": "delivered"}
last_order = recent_orders.popitem()
print(last_order) # Output: ('order3', 'delivered')

clear() Method

The clear() method removes all elements from a Python dictionary.

temporary_data = {"session": "abc123", "user": "john_doe"}
temporary_data.clear()
print(temporary_data) # Output: {}

Dictionary Iteration

Iterating through Python dictionaries is a common operation in data processing and analysis.

Iterating Over Keys

grades = {"Math": 90, "Science": 85, "English": 92}
for subject in grades:
print(f"Subject: {subject}")

Iterating Over Values

prices = {"apple": 1.50, "banana": 0.80, "orange": 2.00}
for price in prices.values():
print(f"Price: ${price}")

Iterating Over Key-Value Pairs

employee_data = {"name": "Alice", "department": "IT", "salary": 75000}
for key, value in employee_data.items():
print(f"{key}: {value}")

Nested Dictionaries

Python dictionaries can contain other dictionaries as values, creating nested dictionary structures. This feature is particularly useful for representing complex data hierarchies.

company_structure = {
"engineering": {
"manager": "John Smith",
"employees": ["Alice", "Bob", "Charlie"],
"budget": 500000
},
"marketing": {
"manager": "Jane Doe",
"employees": ["David", "Eve"],
"budget": 300000
}
}

# Accessing nested dictionary values
print(company_structure["engineering"]["manager"]) # Output: John Smith

Dictionary Membership Testing

Python dictionaries support membership testing using the in operator, which checks if a key exists in the dictionary.

library_books = {"Python": 5, "JavaScript": 3, "Java": 8}
if "Python" in library_books:
print(f"Python books available: {library_books['Python']}")

# Checking if key doesn't exist
if "Ruby" not in library_books:
print("Ruby books are not available")

Dictionary Length and Boolean Conversion

You can determine the size of Python dictionaries using the len() function and check if a dictionary is empty using boolean conversion.

contact_list = {"Alice": "alice@email.com", "Bob": "bob@email.com"}
print(len(contact_list)) # Output: 2

empty_dict = {}
if not empty_dict:
print("Dictionary is empty")

Complete Python Dictionary Example

Here’s a comprehensive example demonstrating various Python dictionary operations in a real-world scenario:

# Required imports
from datetime import datetime

# Complete Python Dictionary Example: Library Management System
class LibraryManager:
def __init__(self):
# Initialize library catalog as nested dictionaries
self.catalog = {
"fiction": {
"The Great Gatsby": {"author": "F. Scott Fitzgerald", "copies": 5, "borrowed": 2},
"To Kill a Mockingbird": {"author": "Harper Lee", "copies": 3, "borrowed": 1},
"1984": {"author": "George Orwell", "copies": 4, "borrowed": 3}
},
"non_fiction": {
"Sapiens": {"author": "Yuval Noah Harari", "copies": 6, "borrowed": 2},
"The Immortal Life of Henrietta Lacks": {"author": "Rebecca Skloot", "copies": 2, "borrowed": 1}
},
"science": {
"A Brief History of Time": {"author": "Stephen Hawking", "copies": 3, "borrowed": 0},
"The Selfish Gene": {"author": "Richard Dawkins", "copies": 2, "borrowed": 1}
}
}

# Dictionary to track borrowed books
self.borrowed_books = {}

# Dictionary to store member information
self.members = {
"member001": {"name": "Alice Johnson", "email": "alice@email.com", "books_borrowed": []},
"member002": {"name": "Bob Wilson", "email": "bob@email.com", "books_borrowed": []},
"member003": {"name": "Charlie Brown", "email": "charlie@email.com", "books_borrowed": []}
}

def display_catalog(self):
"""Display all books in the catalog"""
print("=== Library Catalog ===")
for category, books in self.catalog.items():
print(f"\n{category.upper()} BOOKS:")
for title, details in books.items():
available = details["copies"] - details["borrowed"]
print(f" - {title} by {details['author']}")
print(f" Available: {available}/{details['copies']} copies")

def search_book(self, title):
"""Search for a book across all categories"""
for category, books in self.catalog.items():
if title in books:
book_info = books[title].copy()
book_info["category"] = category
return book_info
return None

def borrow_book(self, member_id, book_title):
"""Process book borrowing"""
if member_id not in self.members:
return "Member not found"

book_info = self.search_book(book_title)
if not book_info:
return "Book not found"

category = book_info["category"]
book_data = self.catalog[category][book_title]

available_copies = book_data["copies"] - book_data["borrowed"]
if available_copies <= 0:
return "No copies available"

# Update borrowed count
self.catalog[category][book_title]["borrowed"] += 1

# Add to member's borrowed books
self.members[member_id]["books_borrowed"].append(book_title)

# Track borrowing details
borrow_key = f"{member_id}_{book_title}"
self.borrowed_books[borrow_key] = {
"member_id": member_id,
"book_title": book_title,
"borrow_date": datetime.now().strftime("%Y-%m-%d"),
"due_date": "2024-08-15" # Example due date
}

return f"Successfully borrowed '{book_title}'"

def return_book(self, member_id, book_title):
"""Process book return"""
borrow_key = f"{member_id}_{book_title}"

if borrow_key not in self.borrowed_books:
return "Book not borrowed by this member"

# Find book in catalog and update
book_info = self.search_book(book_title)
if book_info:
category = book_info["category"]
self.catalog[category][book_title]["borrowed"] -= 1

# Remove from borrowed books tracking
del self.borrowed_books[borrow_key]

# Remove from member's borrowed books
if book_title in self.members[member_id]["books_borrowed"]:
self.members[member_id]["books_borrowed"].remove(book_title)

return f"Successfully returned '{book_title}'"

def get_member_info(self, member_id):
"""Get detailed member information"""
if member_id not in self.members:
return "Member not found"

member = self.members[member_id]
return {
"name": member["name"],
"email": member["email"],
"books_currently_borrowed": len(member["books_borrowed"]),
"borrowed_books": member["books_borrowed"]
}

def get_statistics(self):
"""Generate library statistics"""
total_books = 0
total_borrowed = 0

for category, books in self.catalog.items():
category_total = len(books)
category_borrowed = sum(book["borrowed"] for book in books.values())
total_books += category_total
total_borrowed += category_borrowed

return {
"total_books": total_books,
"total_borrowed": total_borrowed,
"total_members": len(self.members),
"active_borrowings": len(self.borrowed_books)
}

# Example usage and demonstration
if __name__ == "__main__":
# Create library manager instance
library = LibraryManager()

# Display initial catalog
library.display_catalog()

# Search for a book
search_result = library.search_book("1984")
if search_result:
print(f"\nFound book: {search_result}")

# Borrow a book
print(f"\nBorrow result: {library.borrow_book('member001', '1984')}")

# Get member information
member_info = library.get_member_info('member001')
print(f"\nMember info: {member_info}")

# Return a book
print(f"\nReturn result: {library.return_book('member001', '1984')}")

# Get library statistics
stats = library.get_statistics()
print(f"\nLibrary Statistics:")
for key, value in stats.items():
print(f" {key.replace('_', ' ').title()}: {value}")

# Demonstrate dictionary methods
print(f"\nAll categories: {list(library.catalog.keys())}")
print(f"Total members: {len(library.members)}")

# Dictionary comprehension example
available_books = {
title: details["copies"] - details["borrowed"]
for category in library.catalog.values()
for title, details in category.items()
}
print(f"\nAvailable copies per book: {available_books}")

# Expected Output:
# === Library Catalog ===
# 
# FICTION BOOKS:
# - The Great Gatsby by F. Scott Fitzgerald
# Available: 3/5 copies
# - To Kill a Mockingbird by Harper Lee
# Available: 2/3 copies
# - 1984 by George Orwell
# Available: 1/4 copies
# 
# NON_FICTION BOOKS:
# - Sapiens by Yuval Noah Harari
# Available: 4/6 copies
# - The Immortal Life of Henrietta Lacks by Rebecca Skloot
# Available: 1/2 copies
# 
# SCIENCE BOOKS:
# - A Brief History of Time by Stephen Hawking
# Available: 3/3 copies
# - The Selfish Gene by Richard Dawkins
# Available: 1/2 copies
# 
# Found book: {'author': 'George Orwell', 'copies': 4, 'borrowed': 3, 'category': 'fiction'}
# 
# Borrow result: Successfully borrowed '1984'
# 
# Member info: {'name': 'Alice Johnson', 'email': 'alice@email.com', 'books_currently_borrowed': 1, 'borrowed_books': ['1984']}
# 
# Return result: Successfully returned '1984'
# 
# Library Statistics:
# Total Books: 7
# Total Borrowed: 7
# Total Members: 3
# Active Borrowings: 0
# 
# All categories: ['fiction', 'non_fiction', 'science']
# Total members: 3
# 
# Available copies per book: {'The Great Gatsby': 3, 'To Kill a Mockingbird': 2, '1984': 1, 'Sapiens': 4, 'The Immortal Life of Henrietta Lacks': 1, 'A Brief History of Time': 3, 'The Selfish Gene': 1}

This comprehensive example demonstrates Python dictionaries in action, showing how they can be used to build complex data structures for real-world applications. The library management system uses nested dictionaries, dictionary methods, and various dictionary operations to manage books, members, and borrowing records efficiently.