A dictionary is a built-in Python data type used to store data in key-value pairs.
Each item in a dictionary consists of:
key : value
For example:
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20
}
Here:
first_name → John
last_name → Doe
age → 20
The key identifies the data, while the value contains the actual data.
1. What is a Dictionary?
A dictionary is useful when we want to store related information using meaningful names instead of numerical indexes.
For example, using a list:
student = ["John", "Doe", 20, "Male"]
It can be difficult to remember what each position represents.
With a dictionary:
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male"
}
The data becomes much easier to understand.
We can directly access the student's age using:
student["age"]
2. Dictionary Characteristics
Python dictionaries have the following important characteristics:
- Store data in key-value pairs.
- Dictionaries are ordered in modern Python versions.
- Dictionaries are mutable.
- Keys must be unique.
- Values can be duplicated.
- Keys can be strings, numbers, tuples, etc., as long as they are hashable.
- Values can be almost any Python data type.
- A dictionary can contain lists, tuples, sets, or even another dictionary as values.
- Dictionaries are accessed using keys, not numerical indexes.
3. Dictionary Syntax
The basic syntax is:
dictionary = {
"key1": "value1",
"key2": "value2"
}
For example:
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20
}
Here:
"first_name"is a key."John"is its value."last_name"is a key."Doe"is its value."age"is a key.20is its value.
4. Creating a Dictionary
Example
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male"
}
print(student)
Output
{'first_name': 'John', 'last_name': 'Doe', 'age': 20, 'gender': 'Male'}
5. Dictionary Keys
Each dictionary key must be unique.
Example
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20
}
Here, all three keys are different.
If you use the same key more than once, the later value replaces the earlier value.
Example
student = {
"name": "John",
"name": "Michael"
}
print(student)
Output
{'name': 'Michael'}
The second "name" replaced the first one.
6. Accessing Dictionary Values
Dictionary values can be accessed using their keys.
Syntax
dictionary["key"]
Example
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male"
}
print(student["first_name"])
print(student["last_name"])
Output
John
Doe
You don't use an index such as student[0].
Instead, you use the key:
student["first_name"]
7. Accessing Multiple Values
You can access multiple values separately.
print(student["first_name"], student["last_name"])
Output
John Doe
8. Creating a Dictionary Using dict()
Python provides the dict() constructor for creating dictionaries.
Example
student = dict({
"first_name": "John",
"last_name": "Doe"
})
print(student)
Output
{'first_name': 'John', 'last_name': 'Doe'}
You can also create a dictionary directly using keyword arguments:
student = dict(
first_name="John",
last_name="Doe",
age=20
)
print(student)
Output
{'first_name': 'John', 'last_name': 'Doe', 'age': 20}
9. Dictionary with Different Data Types
Dictionary values can contain different data types.
Example
student = {
"name": "John",
"age": 20,
"percentage": 85.5,
"is_active": True
}
print(student)
A dictionary can contain:
- Strings
- Integers
- Floats
- Boolean values
- Lists
- Tuples
- Sets
- Other dictionaries
10. Dictionary Containing a List
A dictionary value can be a list.
Example
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male",
"subjects": ["Python", "Django", "REST API"]
}
print(student["subjects"])
Output
['Python', 'Django', 'REST API']
11. Accessing an Element Inside a List
Because "subjects" contains a list, we can use another index to access an individual subject.
print(student["subjects"][0])
Output
Python
Another example:
print(student["subjects"][1])
Output:
Django
This demonstrates that dictionaries and lists can be combined.
12. Finding the Length of a Dictionary
The len() function returns the number of key-value pairs in a dictionary.
Example
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male"
}
print(len(student))
Output
4
There are four key-value pairs.
13. Checking the Data Type
Use the type() function to check the data type.
student = {
"name": "John",
"age": 20
}
print(type(student))
Output
<class 'dict'>
14. Creating an Empty Dictionary
An empty dictionary can be created using {}.
student = {}
print(student)
Output
{}
You can then add data later.
15. Adding a New Key-Value Pair
You can add a new item by assigning a value to a new key.
Example
student = {}
student["name"] = "Michael"
student["address"] = "New York"
print(student)
Output
{'name': 'Michael', 'address': 'New York'}
16. Updating an Existing Value
If the key already exists, assigning a new value will update it.
Example
student = {
"name": "Michael",
"address": "New York"
}
student["address"] = "Kathmandu"
print(student)
Output
{'name': 'Michael', 'address': 'Kathmandu'}
The value of "address" changed from "New York" to "Kathmandu".
17. Adding and Updating Using update()
The update() method can be used to add new key-value pairs or update existing ones.
Example
student = {
"name": "Michael",
"address": "New York"
}
student.update({
"address": "Paris"
})
print(student)
Output
{'name': 'Michael', 'address': 'Paris'}
Adding Multiple Values with update()
student.update({
"age": 25,
"gender": "Male",
"country": "Nepal"
})
print(student)
This allows you to add multiple key-value pairs at once.
18. Adding an Email
You can add any valid string as a dictionary value.
student["email"] = "abc@example.com"
print(student)
Example output:
{'name': 'Michael', 'address': 'Paris', 'email': 'abc@example.com'}
19. Using get() to Access Values
There are two common ways to access dictionary values.
Using square brackets
print(student["name"])
Using get()
print(student.get("name"))
Both return the value if the key exists.
20. Difference Between [] and get()
This is an important difference.
Suppose the key does not exist.
Using []
print(student["phone"])
This produces:
KeyError
Using get()
print(student.get("phone"))
Output:
None
get() is often safer when you are not sure whether a key exists.
You can also provide a default value:
print(student.get("phone", "Not Available"))
Output:
Not Available
21. Checking Whether a Key Exists
Use the in operator to check whether a key exists.
Example
student = {
"name": "John",
"age": 20,
"country": "Nepal"
}
print("name" in student)
print("email" in student)
Output
True
False
You can also use:
print("email" not in student)
Output:
True
22. Removing an Item Using pop()
The pop() method removes a key-value pair using its key.
Example
student = {
"name": "Michael",
"address": "Kathmandu",
"age": 25
}
student.pop("address")
print(student)
Output
{'name': 'Michael', 'age': 25}
23. pop() Returns the Removed Value
The pop() method also returns the value that was removed.
student = {
"name": "John",
"age": 20
}
removed = student.pop("age")
print(removed)
print(student)
Output
20
{'name': 'John'}
24. Removing the Last Item Using popitem()
The popitem() method removes and returns the last inserted key-value pair.
Example
student = {
"name": "John",
"age": 20,
"country": "Nepal"
}
item = student.popitem()
print(item)
print(student)
Output
('country', 'Nepal')
{'name': 'John', 'age': 20}
25. Removing an Item Using del
The del statement can remove a specific key-value pair.
Example
student = {
"name": "John",
"age": 20,
"country": "Nepal"
}
del student["age"]
print(student)
Output
{'name': 'John', 'country': 'Nepal'}
You can also delete the entire dictionary:
del student
After this, the variable student no longer exists.
26. Removing All Items Using clear()
The clear() method removes all key-value pairs but keeps the dictionary itself.
Example
student = {
"name": "John",
"age": 20
}
student.clear()
print(student)
Output
{}
27. del vs clear()
| Operation | Result |
|---|---|
del student["age"] | Removes one key |
student.pop("age") | Removes one key and returns its value |
student.popitem() | Removes the last inserted item |
student.clear() | Removes all items but keeps dictionary |
del student | Deletes the entire dictionary |
28. Getting All Keys Using keys()
The keys() method returns all the keys in a dictionary.
Example
student = {
"name": "John",
"age": 20,
"country": "Nepal"
}
print(student.keys())
Output
dict_keys(['name', 'age', 'country'])
You can convert it into a list:
print(list(student.keys()))
Output:
['name', 'age', 'country']
29. Getting All Values Using values()
The values() method returns all the values.
Example
print(student.values())
Output
dict_values(['John', 20, 'Nepal'])
You can convert them into a list:
print(list(student.values()))
30. Getting Key-Value Pairs Using items()
The items() method returns all key-value pairs.
Example
print(student.items())
Output
dict_items([('name', 'John'), ('age', 20), ('country', 'Nepal')])
Each pair is represented as a tuple:
('name', 'John')
31. Looping Through Dictionary Keys
You can loop through a dictionary directly to get its keys.
Example
student = {
"name": "John",
"age": 20,
"country": "Nepal"
}
for key in student:
print(key)
Output
name
age
country
32. Looping Through Dictionary Values
Use values() when you want only the values.
for value in student.values():
print(value)
Output
John
20
Nepal
33. Looping Through Keys and Values
The items() method is commonly used to access both keys and values.
Example
for key, value in student.items():
print(key, ":", value)
Output
name : John
age : 20
country : Nepal
This is one of the most useful dictionary operations in Python.
34. Nested Dictionary
A dictionary can contain another dictionary as a value.
This is called a nested dictionary.
Example
student = {
"name": "John",
"address": {
"city": "Kathmandu",
"country": "Nepal"
}
}
print(student)
35. Accessing a Nested Dictionary
You can access nested values using multiple keys.
print(student["address"])
Output:
{'city': 'Kathmandu', 'country': 'Nepal'}
To access the city:
print(student["address"]["city"])
Output:
Kathmandu
To access the country:
print(student["address"]["country"])
Output:
Nepal
36. Multiple Levels of Nested Dictionaries
Dictionaries can be nested multiple levels deep.
Your original example:
test = {
"key1": {
"nestkey": {
"subnestkey": "final result"
}
}
}
Accessing each level:
print(test["key1"])
Output:
{'nestkey': {'subnestkey': 'final result'}}
print(test["key1"]["nestkey"])
Output:
{'subnestkey': 'final result'}
print(test["key1"]["nestkey"]["subnestkey"])
Output:
final result
37. Dictionary Containing a List of Dictionaries
This is very common when working with APIs and databases.
Example
students = {
"students": [
{
"name": "John",
"age": 20
},
{
"name": "Michael",
"age": 22
}
]
}
Accessing the first student:
print(students["students"][0])
Output:
{'name': 'John', 'age': 20}
Accessing the first student's name:
print(students["students"][0]["name"])
Output:
John
This structure is extremely common when working with JSON and REST APIs.
38. Dictionary vs JavaScript Object
If you have experience with JavaScript, a Python dictionary is conceptually similar to a JavaScript object.
Python
student = {
"name": "John",
"age": 20
}
print(student["name"])
JavaScript
const student = {
name: "John",
age: 20
};
console.log(student.name);
They are similar in concept, but they are not exactly the same data structure.
Python calls it a dictionary (dict), while JavaScript commonly uses objects for this kind of key-value data.
39. Copying a Dictionary
Assigning a dictionary to another variable does not create an independent copy.
Example
student = {
"name": "John",
"age": 20
}
student2 = student
student2["age"] = 25
print(student)
Output:
{'name': 'John', 'age': 25}
Both variables refer to the same dictionary.
To create a shallow copy, use copy().
Example
student = {
"name": "John",
"age": 20
}
student2 = student.copy()
student2["age"] = 25
print(student)
print(student2)
Output:
{'name': 'John', 'age': 20}
{'name': 'John', 'age': 25}
40. Creating a Dictionary Using fromkeys()
The fromkeys() method creates a dictionary from a sequence of keys.
Example
keys = ["name", "age", "country"]
student = dict.fromkeys(keys)
print(student)
Output
{'name': None, 'age': None, 'country': None}
You can also provide a default value:
student = dict.fromkeys(keys, "Not Available")
print(student)
Output:
{'name': 'Not Available', 'age': 'Not Available', 'country': 'Not Available'}
41. Dictionary Methods
Here are the most important dictionary methods:
| Method | Description |
|---|---|
get() | Returns the value of a key |
keys() | Returns all keys |
values() | Returns all values |
items() | Returns key-value pairs |
update() | Adds or updates items |
pop() | Removes a specified key |
popitem() | Removes the last inserted item |
clear() | Removes all items |
copy() | Creates a shallow copy |
fromkeys() | Creates a dictionary from keys |
42. Dictionary Example
Here is a complete example combining several concepts:
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male",
"subjects": ["Python", "Django", "REST API"]
}
print("Student:", student)
print("First Name:", student["first_name"])
print("Last Name:", student["last_name"])
print("Age:", student["age"])
print("Subjects:", student["subjects"])
print("First Subject:", student["subjects"][0])
student["age"] = 21
student["email"] = "john@example.com"
print("Updated Student:", student)
43. Complete Copy Code
# ==========================================
# Python Dictionaries
# ==========================================
# Creating a dictionary
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male"
}
print(student)
# Accessing values
print(student["first_name"])
print(student["last_name"])
# Creating dictionary using dict()
student = dict({
"first_name": "John",
"last_name": "Doe"
})
print(student)
# Dictionary containing a list
student = {
"first_name": "John",
"last_name": "Doe",
"age": 20,
"gender": "Male",
"subjects": ["Python", "Django", "REST API"]
}
print(student["subjects"])
print(student["subjects"][0])
# Empty dictionary
d = {}
d["name"] = "Michael"
d["address"] = "New York"
print(d)
# Updating a value
d["address"] = "Kathmandu"
print(d)
# update()
d.update({
"address": "Paris"
})
print(d)
# Adding a new key
d["email"] = "abc@example.com"
print(d)
# get()
print(d.get("name"))
print(d.get("phone"))
print(d.get("phone", "Not Available"))
# pop()
d.pop("address")
print(d)
# keys()
print(student.keys())
# values()
print(student.values())
# items()
print(student.items())
# Checking key existence
print("first_name" in student)
print("email" in student)
# Length
print(len(student))
# Type
print(type(student))
# Nested dictionary
test = {
"key1": {
"nestkey": {
"subnestkey": "final result"
}
}
}
print(test["key1"])
print(test["key1"]["nestkey"])
print(test["key1"]["nestkey"]["subnestkey"])
# Dictionary containing list
list1 = [5, 15, 25, 35]
list2 = [10, 20, 30, 40]
matrix = [list1, list2]
print(matrix)
print(matrix[1])
print(matrix[1][2])
print(matrix[0][1])
# Loop through keys
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through keys and values
for key, value in student.items():
print(key, ":", value)
44. Practice Exercise
Create a dictionary for a student:
student = {
"name": "Ram",
"age": 22,
"course": "Python",
"marks": 85
}
Perform the following:
- Print the complete dictionary.
- Print the student's name.
- Print the student's age.
- Print the student's course.
- Print the number of key-value pairs.
- Add an
"email"key. - Add a
"city"key. - Change the student's marks to
90. - Use
get()to access the email. - Check whether
"phone"exists. - Print all keys.
- Print all values.
- Print all key-value pairs.
- Remove the
"city"key usingpop(). - Loop through the dictionary and print every key and value.
45. Challenge Exercise
Create a dictionary containing information about three students.
Use a structure like:
students = {
"student1": {
"name": "John",
"age": 20,
"course": "Python"
},
"student2": {
"name": "Ram",
"age": 22,
"course": "Django"
},
"student3": {
"name": "Sita",
"age": 21,
"course": "Data Science"
}
}
Perform the following:
- Print the complete dictionary.
- Print the first student's name.
- Print the second student's course.
- Print the third student's age.
- Add a new student.
- Change the first student's age.
- Add an email to the second student.
- Loop through all students.
- Print each student's name and course.
- Remove one student.
46. Dictionary + List + Nested Dictionary
Real-world Python applications frequently combine dictionaries and lists.
For example:
students = [
{
"name": "John",
"age": 20,
"course": "Python"
},
{
"name": "Ram",
"age": 22,
"course": "Django"
},
{
"name": "Sita",
"age": 21,
"course": "Data Science"
}
]
This is a list containing dictionaries.
You can access the first student's information:
print(students[0])
Output:
{'name': 'John', 'age': 20, 'course': 'Python'}
Access the first student's name:
print(students[0]["name"])
Output:
John
This type of structure is extremely common when working with:
- REST APIs
- JSON data
- Databases
- Django
- Flask
- FastAPI
- Data processing
- Web applications
- objects.
- Work with dictionary structures commonly returned by APIs and JSON.