A dictionary in Python is a collection of key-value pairs. Think of it as a real dictionary —you look up a word (key) to get its definition (value)!
Why Use Dictionaries?
- Fast lookups
- Stores data in key-value pairs
- Flexible and easy to use
Creating a Dictionary
Dictionaries are created using curly brackets {}
.
dog = {"name": "Buddy", "age": 3, "breed": "Golden Retriever"}
print(dog) # Outputs: {'name': 'Buddy', 'age': 3, 'breed': 'Golden Retriever'}
Accessing Values
Use the key to access a value.
print(dog["name"]) # Outputs: Buddy
Adding and Modifying Items
Dictionaries are mutable, so you can modify them!
dog["color"] = "golden" # Adds a new key-value pair
dog["age"] = 4 # Modifies an existing value
print(dog)
Removing Items
Use del
, .pop()
, or .popitem()
.
del dog["breed"] # Removes 'breed'
age = dog.pop("age") # Removes and returns 'age'
print(dog)
Looping Through a Dictionary
You can loop through keys, values, or both!
for key, value in dog.items():
print(f"{key}: {value}")
Dictionary Methods
keys()
– Get all keys:
print(dog.keys()) # Outputs: dict_keys(['name', 'color'])
values()
– Get all values:
print(dog.values()) # Outputs: dict_values(['Buddy', 'golden'])
items()
– Get all key-value pairs:
print(dog.items())
Summary
Concept | Description |
---|---|
Dictionary | A collection of key-value pairs |
Mutable | Can be modified after creation |
Methods | .keys() , .values() , .items() , .pop() |
0 Comments