Dictionaries are unordered collections of data that store items in key-value pairs. They are incredibly powerful for organizing and quickly accessing related information.
π Ideal for representing real-world objects with unique identifiers (keys).
πΉ 1. What is a Dictionary?
A mutable, unordered collection where each item has a unique
key and an associated value. Defined by curly braces {}.Example:
person = {"name": "Alice", "age": 30, "city": "New York"}
print(person)Output:
{'name': 'Alice', 'age': 30, 'city': 'New York'}πΉ 2. Accessing Dictionary Items
Access values using their associated
key inside square brackets [] or with the .get() method.Example:
student = {"id": 101, "name": "Bob", "grade": "A"}
print(student["name"])
print(student.get("grade"))Output:
BobAπΉ 3. Adding and Modifying Items
To add a new item, assign a value to a new key. To modify, assign a new value to an existing key.
Example:
car = {"brand": "Ford", "model": "Mustang"}
car["year"] = 2020 # Add new item
car["model"] = "Explorer" # Modify existing item
print(car)Output:
{'brand': 'Ford', 'model': 'Explorer', 'year': 2020}πΉ 4. Removing Items
β’
del dict[key]: Removes the item with the specified key.β’
.pop(key): Removes (and returns) the item with the specified key.β’
.clear(): Empties the entire dictionary.Example:
settings = {"theme": "dark", "sound": "on", "notifications": "off"}
del settings["sound"] # Remove by key
print(settings)
settings.pop("theme") # Also removes by key
print(settings)Output:
{'theme': 'dark', 'notifications': 'off'}{'notifications': 'off'}πΉ 5. Looping Through a Dictionary
You can loop through keys, values, or both (items).
Example:
for k, v in person.items(): # Loops through key-value pairs
print(f"{k}: {v}")
Output:
name: Aliceage: 30city: New Yorkπ― Today's Goal(What you should do)
βοΈ Understand how dictionaries store data in key-value pairs
βοΈ Add, access, modify, and remove dictionary items
βοΈ Iterate over keys, values, or items