π 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
dict.keys()
β Returns all keysdict.values()
β Returns all valuesdict.items()
β Returns all key-value pairsdict.get(key)
β Safely get a value without error if the key doesnβt exist
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.