Experiment No.
9 Date:
28/04/2025
BASIC OPERATIONS ON DICTIONARIES
AIM:
THEORY:
Dictionaries are one of the most powerful and widely used data structures in Python,
particularly for storing and managing key-value pairs. Unlike sequences such as lists and
tuples, dictionaries provide efficient lookups by associating unique keys with values,
allowing rapid access to data without requiring iteration.
Dictionaries support heterogeneous data, meaning values can be of various types,
including integers, strings, lists, or even other dictionaries. They are ideal for
organizing structured information like student records, configurations, word
frequencies, or API responses, where fast retrieval based on specific keys is needed.
Since dictionary keys must be unique and hashable, they enable reliable indexing
and reduce redundancy when managing data.
A key distinction from lists and tuples is that dictionaries are unordered (before
Python 3.7) but optimized for fast access, making them suitable for mapping
relationships rather than maintaining sequential order. Unlike lists, which rely on
indexing by position, dictionaries map keys directly to values, improving efficiency in
search-heavy tasks like handling large datasets or real-time computations.
Additionally, dictionaries support dynamic modification, allowing insertion, deletion,
and updates without disrupting the structure—something tuples cannot do due to
their immutability. This flexibility makes dictionaries indispensable for tasks requiring
fast data retrieval, flexible key-based organization, and structured storage, such as
database-like operations and JSON data processing.
Syntax
A tuple is created using normal brackets (), with elements separated by commas:
Use dict[key] or [Link](key, default) to fetch/access values.
Available Operations
As we know, unlike tuples, dictionaries store data as key-value pairs, allowing for
quick lookups and dynamic modifications. Some key operations include searching
using the in keyword to check if a key exists, while get() allows safe retrieval
without errors. One can use pop(key ) to remove and return a value, or del dict[key]
for deletion. Also, keys(), values(), and items() allow iteration over dictionary
contents. copy() makes a duplicate dictionary, while dictionary unpacking ({ **dict}
) creates new independent copies. While dictionaries themselves are unordered
(before Python 3.7), sorting can be achieved using sorted( [Link]() ) .Functions
like min([Link]()) and max([Link]()) help retrieve numerical extremes.
Finally, setdefault() assigns a default value if a key doesn’t exist, and popitem()
removes the last inserted key-value pair.
Distinctive Features
As discussed, Dictionaries in Python stand out from other data structures due to
their key-value mapping and efficient lookups. This allowing quick data retrieval,
because it uses a hash table internally, enabling constant-time lookups (O(1)) for
accessing elements via keys. Dictionaries also support nesting. That is dictionary can
have/contain other dictionaries. Also, dictionaries offer 8 unique methods that other
data structures do not offer, discussed on the next page.
1: A Python program to create a dictionary with employee details and retrieve the
values upon giving the keys.
# Create dictionary with employee details
employees = {
101: {"name": "Rahul", "designation": "Manager", "salary": 50000},
102: {"name": "Sneha", "designation": "Engineer", "salary": 40000},
103: {"name": "Amit", "designation": "Clerk", "salary": 25000}
}
# Retrieve details using key (employee id)
emp_id = int(input("Enter Employee ID: "))
if emp_id in employees:
emp = employees[emp_id] print("\
nEmployee Details:") print("Name:",
emp["name"]) print("Designation:",
emp["designation"]) print("Salary:",
emp["salary"])
else:
print("Employee not found")
2: Write a Python program to create a user defined dictionary implementing a student
management system(Prompt the user to enter students details into the dictionary).
Decide appropriate keys to be used associated with students(roll-no, name, address and 5
subject marks. Search for student details using roll no as the keys also print the average of
marks student scored. Use for loops into dictionary to print associated values of students
students = {} n = int(input("Enter number of students: "))
# Input student details
for i in range(n):
roll = int(input("\nEnter Roll No: "))
name = input("Enter Name: ") address
= input("Enter Address: ")
marks = [] print("Enter marks of 5
subjects:") for j in range(5):
[Link](int(input()))
students[roll] = {
"name": name,
"address": address,
"marks": marks
}
# Search using roll number search_roll = int(input("\
nEnter roll number to search: "))
if search_roll in students:
student = students[search_roll]
print("\nStudent Details:")
# Using loop to print values for
key, value in [Link]():
print(key, ":", value)
# Calculate average avg = sum(student["marks"]) /
len(student["marks"]) print("Average Marks:", avg)
else:
print("Student not found")
3: Write a python program to implement different methods to process dictionary
elements.
d = {1: "One", 2: "Two", 3: "Three"}
print("Original Dictionary:", d)
# keys() print("\
nKeys:", [Link]())
# values()
print("Values:", [Link]())
# items()
print("Items:",
[Link]())
# update()
[Link]({4: "Four"}) print("\
nAfter update:", d)
# get() print("Value for key 2:",
[Link](2))
# pop()
[Link](3)
print("After pop:",
d)
# popitem()
[Link]()
print("After popitem:",
d)
# clear() [Link]()
print("After clear:",
d)