Dictionaries
Learn how to store and manage data using key-value pairs with Python Dictionaries.
What is a Dictionary?
A Dictionary is a built-in Python data structure used to store data in the form of key-value pairs.
Instead of accessing data using numeric indexes like a List, we access Dictionary values using their keys.
Dictionaries are widely used in real-world applications for storing structured data such as student details, employee records, product information and API responses.
- Stores key-value pairs
- Mutable
- Keys must be unique
- Values can be duplicated
- Keys are used to access values
Dictionary Structure
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
Here:
-
"name"is a key and"Rahul"is its value. -
"age"is a key and22is its value. -
"course"is a key and"Python"is its value.
Creating a Dictionary
Dictionaries are commonly created using
curly braces {}.
student = {
"name": "Rahul",
"age": 22,
"course": "Python",
"city": "Pune"
}
print(student)
Output:
{'name': 'Rahul', 'age': 22, 'course': 'Python', 'city': 'Pune'}
Accessing Dictionary Values
We can access a Dictionary value by using its key inside square brackets.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(student["name"])
print(student["course"])
Output:
Rahul
Python
Using get()
The get() method is useful for
safely accessing a Dictionary value.
student = {
"name": "Rahul",
"course": "Python"
}
print(student.get("name"))
print(student.get("course"))
Output:
Rahul
Python
Missing Key
print(student.get("email"))
Output:
None
Unlike direct bracket access, using
get() returns None
when the key is not found unless a default
value is provided.
Adding a New Key-Value Pair
A new key-value pair can be added by assigning a value to a new key.
student = {
"name": "Rahul",
"course": "Python"
}
student["city"] = "Pune"
print(student)
Output:
{'name': 'Rahul', 'course': 'Python', 'city': 'Pune'}
Updating a Dictionary Value
Since Dictionaries are mutable, existing values can be changed.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
student["age"] = 23
print(student)
Output:
{'name': 'Rahul', 'age': 23, 'course': 'Python'}
Updating using update()
The update() method can update
existing values and add new key-value pairs.
student = {
"name": "Rahul",
"course": "Python"
}
student.update({
"course": "Python Full Stack",
"city": "Pune"
})
print(student)
Output:
{
'name': 'Rahul',
'course': 'Python Full Stack',
'city': 'Pune'
}
Removing Dictionary Items
pop()
The pop() method removes a
specified key and returns its value.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
removed_value = student.pop("age")
print(removed_value)
print(student)
Output:
22
{'name': 'Rahul', 'course': 'Python'}
popitem()
The popitem() method removes and
returns the last inserted key-value pair.
student = {
"name": "Rahul",
"course": "Python",
"city": "Pune"
}
item = student.popitem()
print(item)
print(student)
del
The del statement can remove a
specific key.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
del student["age"]
print(student)
clear()
The clear() method removes all
key-value pairs.
student = {
"name": "Rahul",
"course": "Python"
}
student.clear()
print(student)
Output:
{}
Dictionary keys()
The keys() method returns the
Dictionary's keys.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(student.keys())
We can also loop through the keys:
for key in student.keys():
print(key)
Output:
name
age
course
Dictionary values()
The values() method returns the
Dictionary's values.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
for value in student.values():
print(value)
Output:
Rahul
22
Python
Dictionary items()
The items() method returns
key-value pairs.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
for key, value in student.items():
print(key, ":", value)
Output:
name : Rahul
age : 22
course : Python
Checking if a Key Exists
The in operator can check whether
a key exists in a Dictionary.
student = {
"name": "Rahul",
"course": "Python"
}
print("name" in student)
print("email" in student)
Output:
True
False
Finding Dictionary Length
The len() function returns the
number of key-value pairs.
student = {
"name": "Rahul",
"age": 22,
"course": "Python"
}
print(len(student))
Output:
3
Different Types of Values
Dictionary values can contain different Python data types.
student = {
"name": "Rahul",
"age": 22,
"marks": 85.5,
"passed": True,
"skills": ["Python", "SQL"]
}
print(student)
A Dictionary can therefore represent structuredz real-world information.
List inside a Dictionary
A Dictionary value can itself be a List.
student = {
"name": "Rahul",
"skills": [
"Python",
"SQL",
"Git"
]
}
print(student["skills"])
print(student["skills"][0])
Output:
['Python', 'SQL', 'Git']
Python
Nested Dictionary
A Dictionary can contain another Dictionary as a value.
student = {
"name": "Rahul",
"address": {
"city": "Pune",
"state": "Maharashtra"
}
}
print(student["address"]["city"])
Output:
Pune
List of Dictionaries
A List can contain multiple Dictionaries. This structure is very common in API and database-related applications.
students = [
{
"name": "Rahul",
"course": "Python"
},
{
"name": "Sneha",
"course": ".NET"
},
{
"name": "Amit",
"course": "Java"
}
]
for student in students:
print(
student["name"],
"-",
student["course"]
)
Output:
Rahul - Python
Sneha - .NET
Amit - Java
CIIT Example 🤓📩
Suppose CIIT wants to maintain student information including name, course, fees and placement status.
students = [
{
"name": "Rahul",
"course": "Python",
"fees": 35000,
"placed": True
},
{
"name": "Sneha",
"course": ".NET",
"fees": 35000,
"placed": False
},
{
"name": "Amit",
"course": "Java",
"fees": 30000,
"placed": True
}
]
for student in students:
print("Name:", student["name"])
print("Course:", student["course"])
print("Fees:", student["fees"])
print("Placed:", student["placed"])
print("----------------------")
This type of List + Dictionary structure is commonly used while working with structured application data.
Output:
Name: Rahul
Course: Python
Fees: 35000
Placed: True
----------------------
Name: Sneha
Course: .NET
Fees: 35000
Placed: False
----------------------
Name: Amit
Course: Java
Fees: 30000
Placed: True
----------------------
Dictionary Comprehension Preview
Python also provides a shorter way to create Dictionaries using Dictionary Comprehension.
numbers = [1, 2, 3, 4, 5]
squares = {
number: number * number
for number in numbers
}
print(squares)
Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
Dictionary Comprehension will be covered in detail in the Comprehensions topic.
Important Dictionary Methods
| Method | Purpose |
|---|---|
get() |
Safely access a value |
keys() |
Returns keys |
values() |
Returns values |
items() |
Returns key-value pairs |
update() |
Updates or adds values |
pop() |
Removes a specified key |
popitem() |
Removes the last inserted pair |
clear() |
Removes all items |
copy() |
Creates a shallow copy |
Common Mistakes
- Trying to access a Dictionary using a numeric index like a List.
- Using duplicate keys and expecting multiple separate values for the same key.
- Accessing a missing key directly with square brackets.
- Confusing Dictionary keys with values.
- Forgetting that Dictionary values can themselves contain Lists or Dictionaries.
Interview Points
- What is a Dictionary in Python?
- What is a key-value pair?
- Can Dictionary keys be duplicated?
-
What is the difference between
get()and square bracket access? -
What is the difference between
keys(),values()anditems()? - How do you add and update Dictionary values?
- How do you remove a key from a Dictionary?
- What is a nested Dictionary?
CIIT Learning Point
Dictionaries are one of the most important Python data structures for representing structured information. They are heavily used in APIs, JSON data, databases and real-world applications. Master keys, values, items, nested structures and List-of-Dictionaries patterns before moving to advanced Python.
CIIT Practice Tasks
- Create a Dictionary containing student name, age, course and city.
- Add a new email key to the Dictionary.
- Update the student's course.
-
Remove one key using
pop(). - Print all keys, values and key-value pairs.
- Create a nested Dictionary for student address details.
- Create a List containing five student Dictionaries and display their names.
- From a List of student Dictionaries, display only students whose course is Python.
Summary :
Python Dictionaries store data using unique keys and their corresponding values. They are mutable and support adding, updating, removing and accessing data efficiently. Important methods include get(), keys(), values(), items(), update(), pop(), popitem() and clear(). Dictionaries can also contain Lists and other Dictionaries, making them extremely useful for structured data, JSON, APIs and real-world applications.