Python Dictionary: A Complete Beginner's Guide with Examples
Introduction
Python is one of the most popular programming languages, widely used in web development, automation, data science, and artificial intelligence. One of its most useful built-in data structures is the Dictionary.
A Dictionary allows developers to store and manage information in key-value pairs. Instead of accessing data using numerical indexes like lists, we can retrieve information using meaningful keys.
For example, consider a Student Management System. We need to store student details such as ID, name, department, age, and marks. A Python Dictionary makes it easy to organize and access these details.
In this blog, we will explore Python Dictionaries, including their creation, accessing keys and values, iteration, condition checking, adding, updating, deleting, nested dictionaries, and practical coding examples.
1. What Is a Dictionary in Python?
A Dictionary is a built-in Python data structure that stores information in key-value pairs.
Each key is associated with a value.
Syntax:
dictionary_name = { "key1": "value1", "key2": "value2", "key3": "value3" } Example:
student = { "id": 101, "name": "Ravi", "department": "IT", "age": 22, "marks": 85 } print(student) Output:
{ 'id': 101, 'name': 'Ravi', 'department': 'IT', 'age': 22, 'marks': 85 } Here, id, name, department, age, and marks are keys, while 101, Ravi, IT, 22, and 85 are their corresponding values.
Important characteristics of Dictionary
- Stores data in key-value pairs.
- Keys must be unique.
- Values can be duplicated.
- Dictionaries are mutable, meaning we can modify their contents.
- Dictionaries preserve insertion order.
- Keys must be hashable, such as strings, numbers, or suitable tuples.
- Values can contain different data types.
2. Creating a Dictionary
There are different ways to create a dictionary in Python.
Using curly braces:
student = { "name": "Ravi", "age": 22, "marks": 85 } print(student) Creating an empty dictionary:
student = {} student["name"] = "Ravi" student["age"] = 22 print(student) Using the dict() function:
student = dict(name="Ravi", age=22, marks=85) print(student) All three approaches create a dictionary containing student details.
3. Accessing Dictionary Values
We can retrieve values using their corresponding keys. Python provides two common approaches.
Using square brackets []
student = { "name": "Ravi", "age": 22, "marks": 85 } print(student["name"]) print(student["age"]) Output:
Ravi 22 If the specified key does not exist, Python raises a KeyError.
Using the get() method
The get() method retrieves a value without raising an error when a key is missing.
student = { "name": "Ravi", "age": 22 } print(student.get("name")) print(student.get("department")) print(student.get("department", "Not Available")) Output:
Ravi None Not Available The main difference is that square brackets raise a KeyError for a missing key, whereas get() returns None by default or a specified default value.
4. Understanding Keys and Values
Python provides three important methods to work with dictionary elements.
keys()
The keys() method returns all keys in a dictionary.
student = { "id": 101, "name": "Ravi", "department": "IT", "marks": 85 } print(student.keys()) Output:
dict_keys(['id', 'name', 'department', 'marks']) values()
The values() method returns all values in a dictionary.
print(student.values()) Output:
dict_values([101, 'Ravi', 'IT', 85]) items()
The items() method returns all key-value pairs as tuples.
print(student.items()) Output:
dict_items([ ('id', 101), ('name', 'Ravi'), ('department', 'IT'), ('marks', 85) ]) These three methods are especially useful when working with dictionary data.
5. Iterating Through a Dictionary
Iteration means accessing dictionary elements one by one using a loop.
Python supports different approaches to dictionary iteration.
Iterating through keys
When we directly use a dictionary inside a for loop, Python iterates through its keys.
student = { "name": "Ravi", "age": 22, "department": "IT" } for key in student: print(key) Output:
name age department We can also use student.keys() to achieve the same result.
Iterating through values
If we only want the values, we can use the values() method.
for value in student.values(): print(value) Output:
Ravi 22 IT Iterating through keys and values
If we need both keys and values, we can use the items() method.
for key, value in student.items(): print(key, ":", value) Output:
name : Ravi age : 22 department : IT Here, the first variable receives the key and the second variable receives its corresponding value.
6. Condition Checking in Dictionary
Condition checking helps us identify whether a particular key or value exists in a dictionary.
Checking whether a key exists
We use the in operator to check whether a key is present.
student = { "name": "Ravi", "age": 22, "department": "IT" } if "name" in student: print("Name exists") else: print("Name does not exist") Output:
Name exists Checking whether a key does not exist
We use the not in operator.
if "marks" not in student: print("Marks not found") else: print("Marks found") Output:
Marks not found Checking whether a value exists
To check whether a particular value is present, we use values().
if "Ravi" in student.values(): print("Student found") else: print("Student not found") Output:
Student found Remember that in directly on a dictionary checks keys, not values.
7. Adding and Updating Dictionary Elements
Dictionaries are mutable, so we can add new elements and modify existing values.
Adding elements
We can add a new key-value pair using square brackets.
student = { "name": "Ravi", "age": 22 } student["department"] = "IT" student["marks"] = 85 print(student) Output:
{'name': 'Ravi', 'age': 22, 'department': 'IT', 'marks': 85} Updating existing elements
We can update a value by assigning a new value to an existing key.
student["marks"] = 95 print(student) Output:
95 Using update()
The update() method allows us to add or modify multiple key-value pairs.
student.update({ "age": 23, "marks": 90 }) print(student) The update() method modifies existing keys and adds new keys when necessary.
8. Removing Elements from a Dictionary
Python provides several methods to remove dictionary elements.
pop()
Removes a specified key and returns its value.
student = { "name": "Ravi", "age": 22, "marks": 85 } student.pop("age") print(student) popitem()
Removes and returns the last inserted key-value pair.
student.popitem() print(student) del keyword
Deletes a specified key-value pair.
del student["name"] print(student) clear()
Removes all elements from the dictionary.
student.clear() print(student) Output:
{} 9. Nested Dictionary
A nested dictionary means storing one dictionary inside another dictionary.
It is useful when managing multiple records, such as students, employees, and products.
Example: Student Management System
students = { 101: { "name": "Ravi", "department": "IT", "marks": 85 }, 102: { "name": "Kumar", "department": "CSE", "marks": 90 }, 103: { "name": "Arun", "department": "ECE", "marks": 75 } } print(students[101]["name"]) print(students[102]["marks"]) Output:
Ravi 90 We can also iterate through a nested dictionary.
for student_id, details in students.items(): print("Student ID:", student_id) for key, value in details.items(): print(key, ":", value) print() This approach is commonly used when handling structured data and JSON responses from backend APIs.
10. Useful Dictionary Functions and Methods
Some additional built-in functions and dictionary methods are important for everyday programming.
| Method or function | Purpose |
|---|---|
len(d) | Returns the number of key-value pairs |
get() | Retrieves a value |
keys() | Returns all keys |
values() | Returns all values |
items() | Returns key-value pairs |
update() | Adds or updates elements |
pop() | Removes a specified key |
popitem() | Removes the last inserted pair |
clear() | Removes all elements |
copy() | Creates a shallow copy |
setdefault() | Returns a value or inserts a default |
fromkeys() | Creates a dictionary from given keys |
Example using len():
student = { "name": "Ravi", "age": 22, "marks": 85 } print(len(student)) Output:
3 11. Real-World Coding Example: Employee Management System
Let's combine the dictionary concepts we have learned to create a simple Employee Management System.
employees = { 101: { "name": "Ravi", "department": "IT", "salary": 25000 }, 102: { "name": "Kumar", "department": "HR", "salary": 30000 }, 103: { "name": "Arun", "department": "IT", "salary": 28000 } } # Display all employees for emp_id, details in employees.items(): print("Employee ID:", emp_id) print("Name:", details["name"]) print("Department:", details["department"]) print("Salary:", details["salary"]) print("-------------------") # Search employee search_id = 102 if search_id in employees: print("Employee Found") print("Name:", employees[search_id]["name"]) else: print("Employee Not Found") # Update salary employees[101]["salary"] = 35000 print("Updated Salary:", employees[101]["salary"]) This example combines dictionary creation, nested dictionaries, iteration, condition checking, accessing values, and updating elements.
These operations are frequently used in real-world backend applications.
12. Common Dictionary Coding Interview Problems
Practising dictionary-based problems helps beginners improve their logical thinking and programming skills.
Problem 1: Count the frequency of characters
Question: Count how many times each character appears in a string.
text = "programming" frequency = {} for char in text: if char in frequency: frequency[char] = frequency[char] + 1 else: frequency[char] = 1 print(frequency) Output:
{ 'p': 1, 'r': 2, 'o': 1, 'g': 2, 'a': 1, 'm': 2, 'i': 1, 'n': 1 } Explanation:
- Create an empty dictionary.
- Iterate through every character in the string.
- Check whether the character already exists.
- If it exists, increase its count by one.
- Otherwise, insert the character with a value of one.
Problem 2: Find the student with the highest marks
students = { "Ravi": 85, "Kumar": 90, "Arun": 75, "Priya": 95 } highest = 0 topper = "" for name, marks in students.items(): if marks > highest: highest = marks topper = name print("Topper:", topper) print("Highest Marks:", highest) Output:
Topper: Priya Highest Marks: 95 Problem 3: Find students with marks greater than 50
marks = { "Ravi": 85, "Kumar": 40, "Arun": 75, "Priya": 35 } for name, mark in marks.items(): if mark > 50: print(name, mark) Output:
Ravi 85 Arun 75 Problem 4: Merge two dictionaries
dict1 = { "name": "Ravi", "age": 22 } dict2 = { "department": "IT", "marks": 85 } dict1.update(dict2) print(dict1) Output:
{ 'name': 'Ravi', 'age': 22, 'department': 'IT', 'marks': 85 } 13. Time Complexity of Python Dictionary
Python Dictionaries use hash tables internally to store and retrieve data efficiently.
| Operation | Average Time Complexity |
|---|---|
| Insert | O(1) |
| Access | O(1) |
| Update | O(1) |
| Delete | O(1) |
| Search key | O(1) |
| Iterate through dictionary | O(n) |
These are average-case complexities. In collision-heavy situations, individual operations can take O(n).
14. Real-World Applications of Python Dictionary
Python Dictionaries are used in many areas of software development.
- Student Management Systems: Store student IDs and their personal or academic details.
- Employee Management Systems: Store employee IDs, names, departments, and salaries.
- URL Shorteners: Store short codes as keys and original URLs as values.
- E-commerce Applications: Store product IDs and product information.
- Frequency Counting: Count how many times characters or elements appear.
- API Development: Handle JSON request and response data.
- Caching: Store previously retrieved information for faster access.
Conclusion
Python Dictionary is one of the most important built-in data structures for storing and managing information in key-value pairs.
Understanding dictionary operations such as keys(), values(), items(), iteration, condition checking, adding, updating, deleting, and nested dictionaries is essential for every Python developer.
Dictionaries are widely used in backend development, API integration, automation, data processing, and real-world software applications.
For beginners, practising dictionary-based coding problems is an excellent way to strengthen programming fundamentals and improve problem-solving skills.
Keep learning, keep coding, and build your programming fundamentals step by step!