Python Dictionaries
Table of Contents
Description
A dictionary in Python is an unordered, mutable, and indexed collection of key-value pairs. Each key must be unique and immutable (like strings, numbers, or tuples), while the values can be of any data type. "Dictionaries are defined using curly braces {} with key-value pairs separated by colons :"
Prerequisites
- Understanding of variables and data types.
- Familiarity with sets, lists, or basic Python syntax.
Examples
Here's a simple program in Python:
# Creating a dictionary
student = {
"name": "Alice",
"age": 21,
"major": "AI"
}
# Accessing values by key
print(student["name"]) # Output: Alice
# Using get() method to safely access values
print(student.get("grade", "Not Found")) # Output: Not Found
# Modifying values
student["age"] = 22
# Adding new key-value pairs
student["grade"] = "A"
# Removing a key-value pair
student.pop("major") # Removes "major" entry
# Looping through dictionary
for key, value in student.items():
print(key, ":", value)
# Dictionary keys, values, and items
print(student.keys()) # Output: dict_keys(['name', 'age', 'grade'])
print(student.values()) # Output: dict_values(['Alice', 22, 'A'])
print(student.items()) # Output: dict_items([('name', 'Alice'), ('age', 22), ('grade', 'A')])
# Nested dictionary
record = {
"id": 101,
"info": {
"name": "Bob",
"department": "CSE"
}
}
print(record["info"]["name"]) # Output: Bob
Real-World Applications
Representing structured data like JSON or database records.
Mapping usernames to passwords or user data.
Caching results for faster lookup.
Implementing key-value storage systems.
Data wrangling in machine learning and data science.
Where topic Can Be Applied
APIs: Storing response data in JSON format.
Web development: Handling form data and user session
Data science: Data wrangling and feature mapping.
Cybersecurity: IP address–login time mappings.
AI/ML: Feature-label or configuration mappings.
Resources
Topic video source
A comprehensive video
Watch
Python pdf
pdf on topic
Visit
Interview Questions
What is a dictionary in Python?
How are dictionaries different from lists or sets?
Can dictionary keys be mutable?
What does get() do, and how is it useful?
How do you create a nested dictionary?