Dictionaries store data as key-value pairs in Python. They are useful for organizing, retrieving, and updating data efficiently. In this Python Dictionary Practice Questions with Solutions set, you’ll learn dictionary creation, accessing values, updating items, removing elements, and common dictionary methods through beginner-friendly practice questions.
1. Python Program to Create and Print a Dictionary
Problem Statement
Write a Python program to create a dictionary containing a student’s name, age, and course, then print it.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(student)
Sample Output
{'name': 'John', 'age': 20, 'course': 'Python'}
Explanation
A dictionary stores data in key-value pairs using curly braces {}.
Concepts Covered
- Dictionary Creation
- Key-Value Pairs
2. Python Program to Access a Dictionary Value
Problem Statement
Write a Python program to print the value of the "course" key.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(student["course"])
Sample Output
Python
Explanation
Values can be accessed using their corresponding keys.
Concepts Covered
- Dictionary Access
3. Python Program to Add a New Key-Value Pair
Problem Statement
Write a Python program to add a new key "city" with the value "Delhi" to a dictionary.
Python Solution
student = {
"name": "John",
"age": 20
}
student["city"] = "Delhi"
print(student)
Sample Output
{'name': 'John', 'age': 20, 'city': 'Delhi'}
Explanation
Assigning a new key automatically adds it to the dictionary.
Concepts Covered
- Adding Items
4. Python Program to Update a Dictionary Value
Problem Statement
Write a Python program to update the age of a student from 20 to 21.
Python Solution
student = {
"name": "John",
"age": 20
}
student["age"] = 21
print(student)
Sample Output
{'name': 'John', 'age': 21}
Explanation
Assigning a new value to an existing key updates that value.
Concepts Covered
- Updating Dictionary Values
5. Python Program to Remove an Item from a Dictionary
Problem Statement
Write a Python program to remove the "age" key from a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
student.pop("age")
print(student)
Sample Output
{'name': 'John', 'course': 'Python'}
Explanation
The pop() method removes the specified key and its value.
Concepts Covered
- pop()
6. Python Program to Print All Dictionary Keys
Problem Statement
Write a Python program to print all keys of a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(student.keys())
Sample Output
dict_keys(['name', 'age', 'course'])
Explanation
The keys() method returns all dictionary keys.
Concepts Covered
- keys()
7. Python Program to Print All Dictionary Values
Problem Statement
Write a Python program to print all values of a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
print(student.values())
Sample Output
dict_values(['John', 20, 'Python'])
Explanation
The values() method returns all values stored in the dictionary.
Concepts Covered
- values()
8. Python Program to Print All Key-Value Pairs
Problem Statement
Write a Python program to print all key-value pairs in a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
for key, value in student.items():
print(key, ":", value)
Sample Output
name : John
age : 20
course : Python
Explanation
The items() method returns both keys and values together.
Concepts Covered
- items()
- for Loop
9. Python Program to Check Whether a Key Exists
Problem Statement
Write a Python program to check whether the key "course" exists in a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python"
}
if "course" in student:
print("Key Found")
else:
print("Key Not Found")
Sample Output
Key Found
Explanation
The in operator checks whether a key exists in the dictionary.
Concepts Covered
- Membership Operator
10. Python Program to Count the Total Number of Key-Value Pairs
Problem Statement
Write a Python program to count the total number of key-value pairs in a dictionary.
Python Solution
student = {
"name": "John",
"age": 20,
"course": "Python",
"city": "Delhi"
}
print("Total Items:", len(student))
Sample Output
Total Items: 4
Explanation
The len() function returns the total number of key-value pairs in the dictionary.
Concepts Covered
- len()
- Dictionary Size
11. Python Program to Find the Student with the Highest Marks
Problem Statement
Write a Python program to find the student who has scored the highest marks using a dictionary.
Python Solution
students = {
"Rahul": 85,
"Priya": 92,
"Aman": 78,
"Neha": 95,
"Rohit": 88
}
top_student = max(students, key=students.get)
print("Top Student:", top_student)
print("Highest Marks:", students[top_student])
Sample Output
Top Student: Neha
Highest Marks: 95
Explanation
The max() function with key=students.get returns the key whose value is the highest.
Concepts Covered
- Dictionary
- max()
- Dictionary Methods
- Key-Value Pairs
12. Python Program to Merge Two Dictionaries and Add Common Values
Problem Statement
Write a Python program to merge two dictionaries. If a key exists in both dictionaries, add their values together.
Python Solution
dict1 = {
"A": 10,
"B": 20,
"C": 30
}
dict2 = {
"B": 15,
"C": 25,
"D": 40
}
result = dict1.copy()
for key, value in dict2.items():
if key in result:
result[key] += value
else:
result[key] = value
print(result)
Sample Output
{'A': 10, 'B': 35, 'C': 55, 'D': 40}
Explanation
The program copies the first dictionary and updates it using the second dictionary. Common keys have their values added together.
Concepts Covered
- Dictionary Merge
- items()
- copy()
- Conditional Statements
13. Python Program to Invert a Dictionary
Problem Statement
Write a Python program to swap the keys and values of a dictionary.
Python Solution
student = {
"Rahul": 101,
"Priya": 102,
"Neha": 103
}
inverted = {}
for key, value in student.items():
inverted[value] = key
print(inverted)
Sample Output
{101: 'Rahul', 102: 'Priya', 103: 'Neha'}
Explanation
The program creates a new dictionary by making each value a key and each key a value.
Concepts Covered
- Dictionary Traversal
- items()
- Dictionary Creation
14. Python Program to Group Words by Their Length
Problem Statement
Write a Python program to group words according to their length using a dictionary.
Python Solution
words = ["apple", "bat", "banana", "cat", "orange", "dog"]
groups = {}
for word in words:
length = len(word)
if length not in groups:
groups[length] = []
groups[length].append(word)
print(groups)
Sample Output
{
3: ['bat', 'cat', 'dog'],
5: ['apple'],
6: ['banana', 'orange']
}
Explanation
Each word is stored in a list based on its length. The dictionary key represents the word length.
Concepts Covered
- Dictionary
- Lists
- append()
- len()
15. Python Program to Count the Frequency of Words in a Sentence
Problem Statement
Write a Python program to count the occurrence of every word in a sentence.
Python Solution
sentence = input("Enter a sentence: ")
words = sentence.lower().split()
frequency = {}
for word in words:
frequency[word] = frequency.get(word, 0) + 1
print("\nWord Frequency:")
for word, count in frequency.items():
print(word, ":", count)
Sample Output
Enter a sentence:
Python is easy and Python is powerful
Word Frequency:
python : 2
is : 2
easy : 1
and : 1
powerful : 1
Explanation
The sentence is converted into lowercase and split into individual words. The get() method counts the frequency of each word efficiently.
Concepts Covered
- Dictionaries
- split()
- get()
- Word Frequency Analysis
16. Python Program to Sort a Dictionary by Values in Descending Order
Problem Statement
Write a Python program to sort a dictionary based on its values in descending order.
Python Solution
students = {
"Rahul": 78,
"Priya": 95,
"Aman": 88,
"Neha": 91,
"Rohit": 82
}
sorted_dict = dict(
sorted(
students.items(),
key=lambda item: item[1],
reverse=True
)
)
print("Dictionary Sorted by Values:")
print(sorted_dict)
Sample Output
Dictionary Sorted by Values:
{'Priya': 95, 'Neha': 91, 'Aman': 88, 'Rohit': 82, 'Rahul': 78}
Explanation
The sorted() function sorts dictionary items using their values, and reverse=True arranges them in descending order.
Concepts Covered
- sorted()
- lambda Function
- Dictionary Sorting
17. Python Program to Find Keys with Duplicate Values
Problem Statement
Write a Python program to find all keys that share duplicate values in a dictionary.
Python Solution
employee = {
"Rahul": "Python",
"Priya": "Java",
"Aman": "Python",
"Neha": "SQL",
"Rohit": "Java"
}
duplicates = {}
for key, value in employee.items():
duplicates.setdefault(value, []).append(key)
print("Keys with Duplicate Values:")
for value, keys in duplicates.items():
if len(keys) > 1:
print(value, ":", keys)
Sample Output
Keys with Duplicate Values:
Python : ['Rahul', 'Aman']
Java : ['Priya', 'Rohit']
Explanation
The program groups keys according to their values and prints only those groups that contain more than one key.
Concepts Covered
- setdefault()
- Dictionary Grouping
- Lists
18. Python Program to Create a Nested Dictionary from Two Lists
Problem Statement
Write a Python program to create a nested dictionary using two lists: one for student names and another for marks.
Python Solution
students = ["Rahul", "Priya", "Aman"]
marks = [85, 92, 78]
result = {}
for i in range(len(students)):
result[students[i]] = {
"Marks": marks[i]
}
print(result)
Sample Output
{
'Rahul': {'Marks': 85},
'Priya': {'Marks': 92},
'Aman': {'Marks': 78}
}
Explanation
The program creates a nested dictionary where each student’s name becomes a key and their marks are stored inside another dictionary.
Concepts Covered
- Nested Dictionary
- Lists
- Looping
- Dictionary Creation
19. Python Program to Find the Average Value of a Dictionary
Problem Statement
Write a Python program to calculate the average of all numeric values stored in a dictionary.
Python Solution
sales = {
"January": 25000,
"February": 32000,
"March": 28000,
"April": 35000
}
average = sum(sales.values()) / len(sales)
print("Average Sales:", average)
Sample Output
Average Sales: 30000.0
Explanation
The values() method returns all dictionary values. Their sum is divided by the total number of entries to calculate the average.
Concepts Covered
- values()
- sum()
- len()
- Dictionary Calculations
20. Python Program to Find the Most Frequently Occurring Value in a Dictionary
Problem Statement
Write a Python program to determine which value appears most frequently in a dictionary.
Python Solution
products = {
"Laptop": "Electronics",
"Mobile": "Electronics",
"Chair": "Furniture",
"Table": "Furniture",
"TV": "Electronics",
"Bed": "Furniture",
"Watch": "Electronics"
}
frequency = {}
for value in products.values():
frequency[value] = frequency.get(value, 0) + 1
most_common = max(frequency, key=frequency.get)
print("Most Frequent Value:", most_common)
print("Count:", frequency[most_common])
Sample Output
Most Frequent Value: Electronics
Count: 4
Explanation
The program counts the occurrence of each dictionary value using another dictionary and then finds the value with the highest frequency using max().
Concepts Covered
- Dictionary Values
- Frequency Counting
- get()
- max()
- Dictionary Traversal
21. Python Program to Create an Inventory Management System Using Dictionaries
Problem Statement
Write a Python program to create a simple inventory management system using dictionaries. Display the available stock and calculate the total inventory value.
Python Solution
inventory = {
"Laptop": {"Price": 55000, "Quantity": 8},
"Mouse": {"Price": 600, "Quantity": 30},
"Keyboard": {"Price": 1200, "Quantity": 20},
"Monitor": {"Price": 15000, "Quantity": 6}
}
total_value = 0
print("Inventory Details\n")
for item, details in inventory.items():
value = details["Price"] * details["Quantity"]
total_value += value
print(f"{item}")
print(f"Price: ₹{details['Price']}")
print(f"Quantity: {details['Quantity']}")
print(f"Total Value: ₹{value}\n")
print("Overall Inventory Value: ₹", total_value)
Sample Output
Inventory Details
Laptop
Price: ₹55000
Quantity: 8
Total Value: ₹440000
Mouse
Price: ₹600
Quantity: 30
Total Value: ₹18000
Keyboard
Price: ₹1200
Quantity: 20
Total Value: ₹24000
Monitor
Price: ₹15000
Quantity: 6
Total Value: ₹90000
Overall Inventory Value: ₹572000
Explanation
The inventory is stored as a nested dictionary. Each product contains its own price and quantity. The program calculates the total value of every product and the overall inventory.
Concepts Covered
- Nested Dictionary
- Dictionary Traversal
- Arithmetic Operations
- Real-world Project
22. Python Program to Find the Employee with the Highest Salary
Problem Statement
Write a Python program to find the employee who has the highest salary from a nested dictionary.
Python Solution
employees = {
"Rahul": {"Salary": 55000},
"Priya": {"Salary": 72000},
"Aman": {"Salary": 68000},
"Neha": {"Salary": 81000}
}
highest = max(
employees,
key=lambda emp: employees[emp]["Salary"]
)
print("Highest Paid Employee:", highest)
print("Salary:", employees[highest]["Salary"])
Sample Output
Highest Paid Employee: Neha
Salary: 81000
Explanation
The program uses the max() function with a lambda expression to compare employee salaries.
Concepts Covered
- Nested Dictionary
- max()
- lambda Function
23. Python Program to Reverse Key-Value Pairs with Duplicate Values
Problem Statement
Write a Python program to reverse a dictionary. If multiple keys have the same value, store them together in a list.
Python Solution
student = {
"Rahul": "Python",
"Aman": "Python",
"Priya": "Java",
"Neha": "SQL",
"Rohit": "Java"
}
reverse = {}
for key, value in student.items():
if value not in reverse:
reverse[value] = []
reverse[value].append(key)
print(reverse)
Sample Output
{
'Python': ['Rahul', 'Aman'],
'Java': ['Priya', 'Rohit'],
'SQL': ['Neha']
}
Explanation
Unlike a normal dictionary inversion, this program preserves duplicate values by storing multiple keys inside a list.
Concepts Covered
- Nested Lists
- Dictionary
- Grouping Data
24. Python Program to Compare Two Dictionaries and Display the Differences
Problem Statement
Write a Python program to compare two dictionaries and display keys whose values are different.
Python Solution
dict1 = {
"Python": 95,
"Java": 80,
"SQL": 90
}
dict2 = {
"Python": 95,
"Java": 88,
"SQL": 85
}
for key in dict1:
if dict1[key] != dict2[key]:
print(key)
print("Dictionary 1:", dict1[key])
print("Dictionary 2:", dict2[key])
print()
Sample Output
Java
Dictionary 1: 80
Dictionary 2: 88
SQL
Dictionary 1: 90
Dictionary 2: 85
Explanation
The program compares corresponding values in two dictionaries and prints only those keys where the values differ.
Concepts Covered
- Dictionary Comparison
- Loops
- Conditional Statements
25. Python Program to Build a Simple Student Result Management System
Problem Statement
Write a Python program to calculate the total marks, average marks, and grade of each student stored in a nested dictionary.
Python Solution
students = {
"Rahul": {"Math": 85, "Science": 90, "English": 88},
"Priya": {"Math": 95, "Science": 98, "English": 94},
"Aman": {"Math": 72, "Science": 76, "English": 80}
}
for name, marks in students.items():
total = sum(marks.values())
average = total / len(marks)
if average >= 90:
grade = "A"
elif average >= 75:
grade = "B"
else:
grade = "C"
print("Student:", name)
print("Total:", total)
print("Average:", round(average, 2))
print("Grade:", grade)
print("-" * 25)
Sample Output
Student: Rahul
Total: 263
Average: 87.67
Grade: B
-------------------------
Student: Priya
Total: 287
Average: 95.67
Grade: A
-------------------------
Student: Aman
Total: 228
Average: 76.0
Grade: B
-------------------------
Explanation
The program uses a nested dictionary to store subject-wise marks, calculates the total and average for each student, and assigns grades based on the average marks.
Concepts Covered
- Nested Dictionary
- sum()
- values()
- Conditional Statements
- Real-world Student Management System
Frequently Asked Questions (FAQs)
1. What is a dictionary in Python?
A dictionary is a built-in Python data structure that stores data as key-value pairs. Each key in a dictionary must be unique, while values can be of any data type. Dictionaries are mutable, meaning you can add, update, or remove elements after creation.
Example:
student = {
"Name": "Rahul",
"Age": 21,
"Course": "Python"
}
print(student)
2. What is the difference between a dictionary and a list in Python?
| Dictionary | List |
|---|---|
| Stores data as key-value pairs | Stores ordered elements |
| Accessed using keys | Accessed using indexes |
| Keys must be unique | Duplicate elements are allowed |
| Faster lookup using keys | Sequential lookup using indexes |
Enclosed in {} | Enclosed in [] |
Dictionaries are best when you need fast access to data using meaningful keys, while lists are ideal for ordered collections.
3. How do you add, update, and delete elements in a dictionary?
You can modify dictionaries easily because they are mutable.
Example:
student = {
"Name": "Rahul",
"Age": 21
}
# Add
student["City"] = "Delhi"
# Update
student["Age"] = 22
# Delete
del student["City"]
print(student)
4. What are the most commonly used dictionary methods in Python?
Some frequently used dictionary methods include:
get()keys()values()items()update()pop()popitem()setdefault()copy()clear()fromkeys()
These methods simplify dictionary operations and improve code readability.
5. What is a nested dictionary?
A nested dictionary is a dictionary that contains one or more dictionaries as its values. It is useful for storing structured or hierarchical data.
Example:
employees = {
"Rahul": {
"Age": 24,
"Department": "IT"
},
"Priya": {
"Age": 26,
"Department": "HR"
}
}
print(employees)
Nested dictionaries are commonly used in JSON data, APIs, and database applications.
6. What is the difference between get() and square bracket [] notation?
Both are used to retrieve dictionary values, but they behave differently.
dictionary[key]raises a KeyError if the key does not exist.dictionary.get(key)returnsNone(or a default value if provided) instead of raising an error.
Example:
student = {
"Name": "Rahul"
}
print(student.get("Age"))
print(student.get("Age", "Not Available"))
Using get() is generally safer when you’re unsure whether a key exists.
7. Can dictionary keys be duplicated?
No. Dictionary keys must always be unique. If the same key is assigned more than once, the latest value overwrites the previous one.
Example:
data = {
"Python": 90,
"Python": 95
}
print(data)
Output:
{'Python': 95}
8. Where are dictionaries used in real-world Python applications?
Dictionaries are widely used in many software applications, including:
- JSON and API responses
- Student Management Systems
- Employee Databases
- Inventory Management
- Banking Applications
- Machine Learning
- Data Analysis
- Web Development
- Configuration Files
- E-commerce Applications
They are one of the most commonly used data structures in professional Python development.
9. What is the average time complexity of dictionary operations?
Python dictionaries are implemented using hash tables, making most operations very efficient.
| Operation | Average Time Complexity |
|---|---|
| Access Value | O(1) |
| Insert Key | O(1) |
| Update Value | O(1) |
| Delete Key | O(1) |
| Search Key | O(1) |
| Iterate Dictionary | O(n) |
This fast lookup capability is one of the biggest advantages of dictionaries.
10. Why are dictionaries important for Python interviews?
Dictionary-based questions are among the most frequently asked in Python interviews because they test your understanding of:
- Hash tables
- Key-value data structures
- Nested dictionaries
- Data manipulation
- Searching and grouping
- Frequency counting
- JSON processing
- Algorithm optimization
- Real-world problem-solving
Mastering dictionaries is essential for careers in Python development, Data Science, Machine Learning, Automation, Web Development, and Backend Engineering. Strong knowledge of dictionary operations will help you write efficient, scalable, and interview-ready Python programs.
Chapter Summary
After completing this chapter, you have learned:
- Dictionary creation
- Accessing values
- Adding key-value pairs
- Updating dictionary values
- Removing items using
pop() keys()values()items()- Checking whether a key exists
- Counting dictionary items
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
