Introduction
One of the most powerful and commonly used data structures is the Dictionary. Dictionaries allow you to store data in key-value pairs, making it easy to organize, retrieve, and update information.
Unlike lists, tuples, and sets, dictionaries use keys instead of indexes to access values. This makes dictionaries ideal for storing structured data such as user profiles, product information, employee records, configuration settings, and much more.
What is a Dictionary in Python?
A dictionary is a collection of data stored as key-value pairs.
Each key acts as a unique identifier, and each key is associated with a value.
Example:
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(student)
Output:
In this example:
- “name” is a key
- “John” is a value
- “age” is a key
- 20 is a value
Why Use Dictionaries?
Dictionaries are useful when:
- Data has a relationship between keys and values
- Fast lookups are required
- Storing structured information
- Managing user records
- Working with JSON data
Example:
Instead of using a list:
student = ["John", 20, "Python"]
Use a dictionary:
student = {
"name": "John",
"age": 20,
"course": "Python"
}
The dictionary is easier to understand and maintain.
Characteristics of Dictionaries
Dictionaries are created using curly braces {}.
Syntax
dictionary_name = {
key1: value1,
key2: value2,
key3: value3
}
Example:
person = {
"name": "Emma",
"city": "Delhi",
"age": 25
}
Creating a Dictionary
1. String Values
student = {
"name": "John",
"course": "Python"
}
print(student)
2. Numeric Values
product = {
"id": 101,
"price": 999
}
print(product)
3. Mixed Data Types
person = {
"name": "John",
"age": 25,
"is_student": True
}
print(person
Dictionaries can store different types of values.
Accessing Dictionary Values
Dictionary values are accessed using keys.
Syntax
dictionary_name[key]
Example:
student = {
"name": "John",
"age": 20
}
print(student["name"])
Output:
Using the get() Method
The get() method safely retrieves a value.
Example:
student = {
"name": "John",
"age": 20
}
print(student.get("name"))
Output:
Difference Between [] and get()
Using []
student["city"]
Output:
Using get()
student.get("city")
Output:
get() is safer.
Adding New Items
You can add new key-value pairs.
Example:
student = {
"name": "John"
}
student["age"] = 20
print(student)
Output:
Updating Dictionary Values
Example:
student = {
"name": "John",
"age": 20
}
student["age"] = 21
print(student)
Output:
Removing Dictionary Items
Use the pop() method.
Example:
student = {
"name": "John",
"age": 20
}
student.pop("age")
print(student)
Output:
Dictionary Length
Use the len() function.
Example:
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(len(student))
Output:
Looping Through a Dictionary
Loop Through Keys
Example:
student = {
"name": "John",
"age": 20
}
for key in student:
print(key)
Output:
age
Loop Through Values
for value in student.values():
print(value)
Output:
20
Loop Through Keys and Values
for key, value in student.items():
print(key, value)
Output:
age 20
Nested Dictionaries
A dictionary can contain another dictionary.
Example:
students = {
"student1": {
"name": "John",
"age": 20
},
"student2": {
"name": "Emma",
"age": 22
}
}
print(students)
Nested dictionaries are useful for complex data structures.
Dictionary Methods
Python provides several built-in methods.
| Method | Description |
|---|---|
get() |
Returns a value by key |
keys() |
Returns all keys |
values() |
Returns all values |
items() |
Returns key-value pairs |
update() |
Updates dictionary |
pop() |
Removes specified key |
popitem() |
Removes last inserted item |
clear() |
Removes all items |
copy() |
Creates a copy |
Example of keys()
student = {
"name": "John",
"age": 20
}
print(student.keys())
Output:
Example of values()
print(student.values())
Output:
Example of items()
print(student.items())
Output:
Real-Life Examples:
1. User Profile
user = {
"username": "john123",
"email": "john@example.com",
"country": "India"
}
print(user["email"])
Output:
Dictionaries are commonly used in user management systems.
2. Product Catalog
product = {
"id": 101,
"name": "Laptop",
"price": 50000
}
print(product["price"])
Output:
This structure is frequently used in e-commerce applications.
Dictionary vs List
| Feature | Dictionary | List |
|---|---|---|
| Storage | Key-Value pairs | Values Only |
| Access | By Key | By Index |
| Duplicate Keys | Not Allowed | Allowed |
| Ordered | Yes | Yes |
| Mutable | Yes | Yes |
Advantages of Dictionaries
- Fast data retrieval
- Easy to organize information
- Flexible structure
- Supports nested data
- Efficient for large datasets
- Commonly used in APIs and JSON
Common Mistakes
1. Using Duplicate Keys
Incorrect:
student = {
"name": "John",
"name": "Emma"
}
Output:
The second key overwrites the first.
2. Accessing Missing Keys
student["city"]
Error:
Use:
student.get("city")
3. Forgetting Quotes Around String Keys
Incorrect:
student = {
name: "John"
}
Error:
Correct:
student = {
"name": "John"
}
4. Confusing Lists and Dictionaries
Incorrect:
student[0]
Dictionaries use keys, not indexes.
Best Practices
1. Use Meaningful Keys
user = {
"first_name": "John"
}
Avoid unclear names.
2. Use get() for Safe Access
user.get("email")
This prevents errors.
3. Keep Keys Consistent
Use a consistent naming style throughout your project.
4. Use Nested Dictionaries for Complex Data
students = {
"student1": {
"name": "John"
}
}
Conclusion
Python dictionaries are one of the most important and versatile data structures in Python. They store information as key-value pairs, making data easy to organize, retrieve, and update. Dictionaries are widely used in web development, APIs, databases, configuration files, and data processing applications.
By understanding dictionary syntax, methods, nested structures, and best practices, you can efficiently manage structured data in your Python programs.
Python Dictionary – Interview Questions
Q 1: What is a dictionary in Python?
Q 2: How do you create a dictionary?
Q 3: Can dictionary keys be duplicated?
Q 4: Are dictionary values mutable?
Q 5: How do you access dictionary values?
Python Dictionary – Objective Questions (MCQs)
Q1. Which of the following correctly creates a dictionary in Python?
Q2. What type of values can a Python dictionary hold?
Q3. Dictionary elements are accessed using:
Q4. What will be the output of the following code?
d = {'a': 1, 'b': 2, 'c': 3}
print(len(d))
Q5. Which of the following statements is true about dictionaries in Python?