📖 What is a Dictionary in Python?
A dictionary is a mutable, unordered collection of data stored as key-value pairs enclosed in curly braces {}.
Keys must be unique and immutable (such as strings or numbers), while values can be of any data type. Dictionaries provide exceptionally fast lookup speeds using hash tables.
1. Basic Dictionary Declaration and Key Access
Create a basic dictionary mapping developer attributes and access values via their unique keys.
Python
# Declaring a dictionary
developer = {
"name": "Nikita",
"role": "Web Developer",
"experience_years": 5,
"active": True
}
print("Developer Name:", developer["name"])
print("Developer Role:", developer["role"])
Output:
Developer Name: Nikita
Developer Role: Web Developer
Real-Time Example 1: User Profile Record Management
Manage user account details dynamically by adding, updating, and removing dictionary keys.
Python
user_profile = {
"username": "tech_lead_99",
"email": "lead@infotech.com",
"status": "Active"
}
# Update a value
user_profile["status"] = "Verified"
# Add a new key-value pair
user_profile["login_count"] = 42
print("Updated Profile Record:")
for key, value in user_profile.items():
print(f" {key}: {value}")
Output:
Updated Profile Record:
username: tech_lead_99
email: lead@infotech.com
status: Verified
login_count: 42
Real-Time Example 2: Product Catalog Price Lookup Database
Look up inventory item pricing rapidly using product code keys with the safe
get() method.
Python
product_prices = {
"P101": 450,
"P102": 1800,
"P103": 1200
}
lookup_code = "P102"
price = product_prices.get(lookup_code, "Product Not Found")
print(f"Price for item code {lookup_code}: ₹{price}")
# Querying a non-existent code safely
missing_price = product_prices.get("P999", "Unavailable")
print(f"Price for unknown code P999: {missing_price}")
Output:
Price for item code P102: ₹1800
Price for unknown code P999: Unavailable
Real-Time Example 3: Application Configuration Settings
Store global application environment parameters in a structured dictionary.
Python
app_config = {
"host": "127.0.0.1",
"port": 8080,
"debug_mode": True,
"allowed_extensions": [".jpg", ".png", ".pdf"]
}
print(f"Server starting on http://{app_config['host']}:{app_config['port']}")
print(f"Debug mode enabled: {app_config['debug_mode']}")
Output:
Server starting on http://127.0.0.1:8080
Debug mode enabled: True
Real-Time Example 4: Word Frequency Counter (Text Analytics)
Count occurrences of words in a log message string using dictionary mapping.
Python
log_message = "error warning error info warning error"
words = log_message.split()
word_counts = {}
for word in words:
word_counts[word] = word_counts.get(word, 0) + 1
print("Log Word Frequencies:")
for word, count in word_counts.items():
print(f" '{word}': {count} time(s)")
Output:
Log Word Frequencies:
'error': 3 time(s)
'warning': 2 time(s)
'info': 1 time(s)
Real-Time Example 5: Nested Dictionaries for JSON-like Structures
Represent complex hierarchical relational records like student report cards using nested dictionaries.
Python
student_records = {
"S001": {
"name": "Amit",
"scores": {"Math": 88, "Science": 92}
},
"S002": {
"name": "Priya",
"scores": {"Math": 95, "Science": 90}
}
}
print(f"Student {student_records['S001']['name']}'s Math Score:", student_records['S001']['scores']['Math'])
print(f"Student {student_records['S002']['name']}'s Science Score:", student_records['S002']['scores']['Science'])
Output:
Student Amit's Math Score: 88
Student Priya's Science Score: 90
Real-Time Example 6: Dictionary Comprehensions
Generate lookup tables dynamically using concise dictionary comprehension syntax.
Python
# Create a mapping of numbers from 1 to 5 to their squares
squares_table = {x: x**2 for x in range(1, 6)}
print("Generated Squares Lookup Table:")
print(squares_table)
Output:
Generated Squares Lookup Table:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Real-Time Example 7: Removing Elements and Clearing Data
Remove temporary session state attributes using
pop() or del.
Python
session_cache = {
"user_id": 1024,
"token": "tok_xyz789",
"temp_otp": "4819"
}
# Remove temporary OTP after verification
removed_otp = session_cache.pop("temp_otp")
print(f"Cleared temporary OTP '{removed_otp}' from session.")
print("Remaining Session Cache:", session_cache)
Output:
Cleared temporary OTP '4819' from session.
Remaining Session Cache: {'user_id': 1024, 'token': 'tok_xyz789'}
Real-Time Example 8: Iterating Over Keys, Values, and Items
Extract keys and values cleanly using built-in dictionary view methods.
Python
http_codes = {200: "OK", 404: "Not Found", 500: "Server Error"}
print("Supported HTTP Status Codes:")
for code, description in http_codes.items():
print(f" Code {code} -> {description}")
Output:
Supported HTTP Status Codes:
Code 200 -> OK
Code 404 -> Not Found
Code 500 -> Server Error
Real-Time Example 9: Merging Two Dictionaries (Python 3.9+)
Combine default settings with custom user overrides using the merge operator
|.
Python
default_theme = {"theme": "light", "notifications": True, "compact": False}
user_overrides = {"theme": "dark", "compact": True}
# Merge dictionaries (user_overrides take precedence)
active_settings = default_theme | user_overrides
print("Merged Active Settings:")
for setting, val in active_settings.items():
print(f" {setting}: {val}")
Output:
Merged Active Settings:
theme: dark
notifications: True
compact: True
Summary of Python Dictionaries
- Key-Value Mapping: Data is organized by unique keys mapped to corresponding values, offering ultra-fast lookups.
- Mutable & Dynamic: Values can be updated, and keys can be added or deleted at runtime.
- Applications: Perfect for JSON payloads, configuration stores, user profiles, counting frequencies, and lookup databases.