πŸ§™β€β™‚οΈ Python Wizard!

Dictionaries

πŸ” Quick Lesson

A dictionary in Python is like a magic spellbook – each spell (key) has a matching incantation (value). Dictionaries let you store data in key-value pairs, making data easy to look up.


1. Creating a Dictionary


                    wizard = {
                        "name": "Gandalf",
                        "age": 2019,
                        "magic_type": "White"
                    }
                

Here, "name", "age", and "magic_type" are keys, and their associated values are "Gandalf", 2019, and "White".


2. Accessing Values

print(wizard["name"])

This will output Gandalf. You can access values using the key inside square brackets.


3. Adding & Modifying Values


                    wizard["staff"] = "Oakwood"
                    wizard["age"] = 2020
                

You can add new key-value pairs or update existing ones just by assignment.


4. Removing Items

del wizard["magic_type"]

This will remove the key "magic_type" from the dictionary.


5. Useful Dictionary Methods

print(wizard.get("robe", "Not found"))

This prints "Not found" if "robe" isn't in the dictionary.


6. Looping Through Dictionaries


                    for key, value in wizard.items():
                        print(f"{key}: {value}")
                

This loops through all key-value pairs in the dictionary.


🧠 Mini Quiz: Test Your Knowledge on Dictionaries

1. What is a dictionary in Python?



2. How do you access the value associated with a key in a dictionary?



3. Which method safely gets a value without causing an error if the key doesn’t exist?