In the previous section, you learned about Python sets and frozensets, which store collections of unique values. However, many real-world applications require storing information in pairs, where one value identifies another. For example, a student’s roll number identifies the student’s name, a product ID identifies its price, and a username identifies an email address. Python provides a powerful built-in data structure called a dictionary to store this type of information.
A dictionary stores data as key-value pairs, making it one of the most useful and frequently used data structures in Python. Dictionaries are widely used in web development, data analysis, machine learning, APIs, automation, configuration files, and database applications because they provide fast and efficient data retrieval using keys.
In this lesson, you will learn what Python dictionaries are, why they are useful, how to create them, understand their characteristics, learn the rules for keys and values, and explore practical examples from real-world programming.
After completing this lesson, you will be able to:
A dictionary is a mutable collection that stores data as key-value pairs. Every key is unique and is associated with exactly one value. Instead of using numeric indexes like lists or tuples, dictionaries use keys to access values.
Dictionaries are ideal for representing structured information where each piece of data has a meaningful name.
Dictionaries make programs easier to read because values are accessed using descriptive keys rather than numeric indexes.
Common applications include:
Dictionaries are created using curly braces {} with keys and values separated by a colon (:).
student = {
"name": "Rahul",
"roll_no": 101,
"course": "BCA",
"marks": 92
}
print(student)
Output
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 92}
Each key uniquely identifies its corresponding value.
dict() Functionstudent = dict(
name="Rahul",
roll_no=101,
course="BCA",
marks=92
)
print(student)
Output
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 92}
student = {}
print(student)
print(type(student))
Output
{}
<class 'dict'>
Empty curly braces create an empty dictionary.
If duplicate keys are provided, the last value replaces the earlier value.
student = {
"name": "Rahul",
"name": "Amit",
"marks": 90
}
print(student)
Output
{'name': 'Amit', 'marks': 90}
The second name key overwrites the first because keys must be unique.
students = {
"student1": 85,
"student2": 85,
"student3": 90
}
print(students)
Output
{'student1': 85, 'student2': 85, 'student3': 90}
Unlike keys, values may be repeated.
Dictionary keys must be immutable. Common valid key types include:
data = {
"name": "Rahul",
101: "Student ID",
True: "Active"
}
print(data)
Mutable objects such as lists, sets, and dictionaries cannot be used as dictionary keys.
data = {
["Python"]: "Programming"
}
Output
TypeError:
unhashable type: 'list'
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student)
Output
{'name': 'Rahul', 'course': 'BCA', 'marks': 92}
product = {
"id": 1001,
"name": "Laptop",
"price": 55000
}
print(product)
Output
{'id': 1001, 'name': 'Laptop', 'price': 55000}
Consider the following program.
employee = {
"name": "Neha",
"department": "HR",
"salary": 50000
}
print(employee)
Execution Steps
Output
{'name': 'Neha', 'department': 'HR', 'salary': 50000}
In this section, you learned what Python dictionaries are, why they are useful, their characteristics, how to create dictionaries using curly braces and the dict() function, the rules for dictionary keys and values, and how dictionaries are used in real-world applications. You also explored execution flow and common beginner mistakes. In the next section, you will learn how to access dictionary values, add and update key-value pairs, remove items, loop through dictionaries, perform membership testing, and apply these techniques in practical Python programs.
In the previous section, you learned how to create Python dictionaries and understand their structure using key-value pairs. Once a dictionary has been created, you can access values, add new key-value pairs, update existing data, remove items, iterate through the dictionary, and check whether a key exists. These operations make dictionaries one of the most flexible and widely used data structures in Python.
In this section, you will learn how to work with dictionary data using practical examples and understand how these operations are applied in real-world Python programs.
Python provides several ways to access, add, update, and remove data from a dictionary. Since dictionaries use keys instead of numeric indexes, every operation is performed using the corresponding key.
The most common way to access a value is by using its key inside square brackets.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student["name"])
print(student["marks"])
Output
Rahul
92
If the specified key does not exist, Python raises a KeyError.
print(student["age"])
Output
KeyError: 'age'
get()The get() method safely returns the value for a given key. If the key does not exist, it returns None or a default value.
student = {
"name": "Rahul",
"marks": 92
}
print(student.get("name"))
print(student.get("age"))
Output
Rahul
None
You can also specify a default value.
print(student.get("age", "Not Available"))
Output
Not Available
Assign a value to a new key to add an item to the dictionary.
student = {
"name": "Rahul"
}
student["course"] = "BCA"
student["marks"] = 92
print(student)
Output
{'name': 'Rahul', 'course': 'BCA', 'marks': 92}
If the key already exists, assigning a new value updates the existing value.
student = {
"name": "Rahul",
"marks": 92
}
student["marks"] = 95
print(student)
Output
{'name': 'Rahul', 'marks': 95}
delThe del statement removes a specified key-value pair.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
del student["course"]
print(student)
Output
{'name': 'Rahul', 'marks': 92}
pop()The pop() method removes a key and returns its value.
student = {
"name": "Rahul",
"marks": 92
}
marks = student.pop("marks")
print(marks)
print(student)
Output
92
{'name': 'Rahul'}
popitem()The popitem() method removes and returns the last inserted key-value pair.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student.popitem())
print(student)
Output
('marks', 92)
{'name': 'Rahul', 'course': 'BCA'}
The clear() method removes every key-value pair from the dictionary.
student = {
"name": "Rahul",
"marks": 92
}
student.clear()
print(student)
Output
{}
The in and not in operators check whether a key exists in a dictionary.
student = {
"name": "Rahul",
"marks": 92
}
print("name" in student)
print("age" in student)
print("age" not in student)
Output
True
False
True
student = {
"name": "Rahul",
"course": "BCA"
}
student["marks"] = 90
print(student)
Output
{'name': 'Rahul', 'course': 'BCA', 'marks': 90}
product = {
"name": "Laptop",
"price": 55000
}
product["price"] = 53000
print(product)
Output
{'name': 'Laptop', 'price': 53000}
employee = {
"name": "Neha",
"department": "HR",
"salary": 50000
}
print(employee.get("salary"))
Output
50000
Consider the following program.
student = {
"name": "Rahul"
}
student["marks"] = 95
print(student)
Execution Steps
marks.95 is assigned to the new key.Output
{'name': 'Rahul', 'marks': 95}
pop() for a key that does not exist.clear() when only one item should be removed.In this section, you learned how to access dictionary values using square brackets and the get() method, add new key-value pairs, update existing values, remove items using del, pop(), and popitem(), clear a dictionary, and perform membership testing using the in operator. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to iterate through dictionaries, use important dictionary methods such as keys(), values(), items(), copy(), and clear(), and work with nested dictionaries.
In the previous section, you learned how to access dictionary values, add new key-value pairs, update existing data, remove items, and perform membership testing. Python also provides several built-in dictionary methods that make it easier to retrieve keys, values, and key-value pairs, create copies, determine the dictionary size, and work with nested dictionaries.
These methods are commonly used in data analysis, web development, APIs, automation, and database applications because they simplify working with structured data.
Python provides several built-in methods for working with dictionaries. The most frequently used methods are:
keys()values()items()copy()clear()len()keys() MethodThe keys() method returns a view containing all dictionary keys.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student.keys())
Output
dict_keys(['name', 'course', 'marks'])
values() MethodThe values() method returns all dictionary values.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student.values())
Output
dict_values(['Rahul', 'BCA', 92])
items() MethodThe items() method returns each key-value pair as a tuple.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(student.items())
Output
dict_items([('name', 'Rahul'), ('course', 'BCA'), ('marks', 92)])
copy() MethodThe copy() method creates a shallow copy of a dictionary.
student = {
"name": "Rahul",
"marks": 92
}
backup = student.copy()
print(backup)
Output
{'name': 'Rahul', 'marks': 92}
clear() MethodThe clear() method removes every key-value pair from a dictionary.
student = {
"name": "Rahul",
"marks": 92
}
student.clear()
print(student)
Output
{}
len() FunctionThe len() function returns the number of key-value pairs in a dictionary.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
print(len(student))
Output
3
Dictionaries can be traversed using a for loop.
student = {
"name": "Rahul",
"course": "BCA",
"marks": 92
}
for key in student:
print(key)
Output
name
course
marks
for value in student.values():
print(value)
Output
Rahul
BCA
92
for key, value in student.items():
print(key, ":", value)
Output
name : Rahul
course : BCA
marks : 92
A dictionary can contain another dictionary as its value. This is called a nested dictionary.
students = {
"student1": {
"name": "Rahul",
"marks": 90
},
"student2": {
"name": "Priya",
"marks": 95
}
}
print(students)
Output
{
'student1': {'name': 'Rahul', 'marks': 90},
'student2': {'name': 'Priya', 'marks': 95}
}
A dictionary can also store lists as values.
student = {
"name": "Rahul",
"subjects": [
"Python",
"SQL",
"Power BI"
]
}
print(student)
Output
{
'name': 'Rahul',
'subjects': ['Python', 'SQL', 'Power BI']
}
employee = {
"name": "Neha",
"department": "HR",
"salary": 50000
}
for key, value in employee.items():
print(key, ":", value)
Output
name : Neha
department : HR
salary : 50000
product = {
"id": 1001,
"name": "Laptop",
"price": 55000
}
print(product.keys())
print(product.values())
Output
dict_keys(['id', 'name', 'price'])
dict_values([1001, 'Laptop', 55000])
get() when a key may not exist.items() when both keys and values are required.items() instead of repeated key lookups inside loops.keys() when values are needed.items() when looping through both keys and values.copy() creates a deep copy.clear() accidentally instead of removing a single item.In this section, you learned how to use important dictionary methods such as keys(), values(), items(), copy(), clear(), and len(). You also learned how to iterate through dictionaries, work with nested dictionaries and dictionaries containing lists, and explored best practices, performance tips, and common beginner mistakes. In the final section, you will review the complete lesson with a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Dictionary Methods: Complete Guide for Beginners.
In this lesson, you learned the fundamentals of Python dictionaries, one of the most powerful and frequently used data structures in Python. Dictionaries store data as key-value pairs, allowing information to be organized, accessed, and updated efficiently using meaningful keys instead of numeric indexes.
You began by understanding what dictionaries are, why they are useful, and how to create them using curly braces and the dict() function. You also learned the rules for dictionary keys and values, including the requirement that keys must be unique and immutable.
Next, you explored how to access dictionary values, add new key-value pairs, update existing values, remove items using different methods, and perform membership testing. These operations make dictionaries highly flexible for managing structured information.
Finally, you learned how to iterate through dictionaries, retrieve keys, values, and key-value pairs using built-in methods, work with nested dictionaries, and store lists inside dictionaries. You also explored best practices, performance tips, and common beginner mistakes.
Dictionaries are essential in Python programming because they provide fast key-based lookups and are widely used in data analysis, APIs, machine learning, web development, and database applications.
get() to access values.del, pop(), or popitem() to remove items.keys(), values(), and items() to retrieve dictionary data.copy() to create a shallow copy.A Python dictionary is a mutable collection that stores data as key-value pairs.
No. Dictionary keys must be unique.
Yes. Multiple keys can have the same value.
Dictionaries are created using curly braces {}.
Use the get() method.
Assign a value to a new key using the assignment operator.
The keys() method.
The items() method.
Yes. These are called nested dictionaries.
Use dictionaries whenever data has meaningful labels such as names, IDs, prices, or configuration settings.
{} and dict().get().del and pop().items().get() and square bracket notation?pop() and popitem().keys(), values(), and items() methods return?Create a Python program that stores and manages student information using dictionaries.
Your program should:
city.keys().values().items().pop().========== STUDENT MANAGEMENT SYSTEM ==========
Student Details
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 92}
After Adding City
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 92, 'city': 'Dehradun'}
After Updating Marks
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 95, 'city': 'Dehradun'}
Dictionary Keys
dict_keys(['name', 'roll_no', 'course', 'marks', 'city'])
Dictionary Values
dict_values(['Rahul', 101, 'BCA', 95, 'Dehradun'])
After Removing City
{'name': 'Rahul', 'roll_no': 101, 'course': 'BCA', 'marks': 95}
================================================
Congratulations! You have successfully learned the fundamentals of Python Dictionaries. You now understand how to create dictionaries, access values, add and update key-value pairs, remove items, iterate through dictionary data, and organize structured information efficiently.
In the next lesson, you will learn Python Dictionary Methods: Complete Guide for Beginners. You will explore advanced dictionary methods such as update(), setdefault(), fromkeys(), pop(), popitem(), copy(), and many more with practical examples and real-world applications.