technical skills grow

Responsive Ads Here

Monday, May 19, 2025

Dictionary practice question step by step

 

🧪 Small Practice Exercises (Try These!)

  1. Create a dictionary with "brand": "Nike", "price": 1200, "color": "Red"

  2. Print the price from the dictionary.

  3. Add a new key "size": "M"

  4. Update the price to 1300

  5. Delete the key "color"

Ans1:

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

  1. car = {"brand": "Toyota", "model": "Corolla", "year": 2022}
  2.  Print both key and value in one line.
  3.  Check if "model" exists as a key.
  4.  Check if "BMW" exists as a value.
  5.  Loop through the values and print them.
  6.  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

Powered by Blogger.

Labels

Contact Form

Name

Email *

Message *

Search This Blog

Blog Archive

Ad Code

Responsive Advertisement

Recent Posts