-
Hajipur, Bihar, 844101
A dictionary is a collection of key-value pairs.
It is unordered, changeable, and indexed.
student = {
"name": "John",
"age": 22,
"course": "Python"
}
print(student)
print(student["name"]) # John
print(student.get("age")) # 22
student["age"] = 23
for key in student:
print(key, student[key])
Or use:
for key, value in student.items():
print(key, value)
if "name" in student:
print("Yes")
print(len(student)) # 3
student["grade"] = "A"
student.pop("course")
del student["age"]
student.clear() # Removes all items
new_dict = student.copy()
students = {
"student1": {"name": "John", "age": 22},
"student2": {"name": "Alice", "age": 21}
}
Create a dictionary, update values, loop through items, and practice nested structures.
Q1. Write a Python program to create a dictionary with keys: "name"
, "age"
, and "city"
.
Q2. Write a Python program to access and print the value of "age"
from the dictionary.
Q3. Write a Python program to change the value of "city"
to "Delhi"
.
Q4. Write a Python program to add a new key "country"
with the value "India"
to the dictionary.
Q5. Write a Python program to remove the key "age"
from the dictionary using pop()
or del
.
Q6. Write a Python program to check if the key "name"
exists in the dictionary.
Q7. Write a Python program to print all key-value pairs in the dictionary using a for
loop.
Q8. Write a Python program to copy one dictionary into another using the copy()
method.
Q9. Write a Python program to create a dictionary with 3 student records, where each student is stored as a nested dictionary.
Q10. Write a Python program to clear all items from a dictionary using the clear()
method.
Q1: What is a dictionary in Python?
Q2: Which symbol is used to define a dictionary?
Q3: How do you access the value of a key?
Q4: What does dict.get("age") do?
Q5: How to remove a key from a dictionary?
Q6: Can a dictionary have duplicate keys?
Q7: Which method gives all keys in the dictionary?
Q8: What does dict.clear() do?
Q9: Can dictionary values be lists or other dictionaries?
Q10: Which method returns both keys and values?