🧪 Small Practice Exercises (Try These!)
-
Create a dictionary with
"brand": "Nike"
,"price": 1200
,"color": "Red"
-
Print the price from the dictionary.
-
Add a new key
"size": "M"
-
Update the price to
1300
-
Delete the key
"color"
dic1 = {"brand": "Nike", "price": 1200, "color": "Red"}
dic1["size"] = "M"
dic1["price"] = 13000
del dic1["color"]
print(dic1)
🧪 Practice Time
Try these and share your answers if you’d like me to review them
- Print both key and value in one line.
- Check if
"model"
exists as a key. - Check if
"BMW"
exists as a value. - Loop through the values and print them.
- Loop through the keys and print them.
car = {"brand": "Toyota", "model": "Corolla", "year": 2022}
##Loop through the keys and print them.
for key in car:
print (f"Key : {key}")
# output :
# Key : brand
# Key : model
# Key : year
#Loop through the values and print them.
for value in car.values():
print ("Values",value)
# values Toyota
# values Corolla
# values 2022
#Print both key and value in one line.
for key,value in car.items():
print (f"{key} : {value}")
#Output:
# brand : Toyota
# model : Corolla
# year : 2022
#Check if "model" exists as a key.
if "model" in car:
print("Yes model is exists")
#Check if "BMW" exists as a value.
if "BMW" in car.values():
print("Yes BMW is exists")
else:
print(f"No")
Step 2: Accessing Nested Data
students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
print(students["student1"]["name"])
print(students["student2"]["name"])
🔹 Step 3: Looping Through Nested Dictionaries
students = {
"student1": {"name": "Alice", "age": 20},
"student2": {"name": "Bob", "age": 22}
}
# print(students["student1"]["name"])
# print(students["student2"]["name"])
for ids , info in students.items():
print(f"{ids} info :")
for key,value in info.items():
print(f"{key} ':' {value} ")
#Output:
student1 info :
name ':' Alice
age ':' 20
student2 info :
name ':' Bob
age ':' 22
No comments:
Post a Comment