1. Creating Dictionaries
A dictionary stores pairs of keys and values. You look a value up by its key.
1.1 Empty Dictionary
my_dict = {}1.2 Dictionary with Initial Values
my_dict = {"name": "Alice", "age": 30}1.3 Dictionary with Mixed Data Types
mixed_dict = {"number": 42, "text": "hello", "flag": True}2. Accessing Elements
2.1 Access by Key
print(my_dict["name"]) # Output: Alice2.2 Safely Access Using .get()
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("profession", "Unknown")) # Output: Unknown if not present.get() returns a default instead of raising an error, which is useful when you are not sure the key is there.
3. Modifying Dictionaries
3.1 Add or Update an Element
my_dict["profession"] = "Engineer" # Adds a new key, or updates it if it exists3.2 Remove Elements
del my_dict["age"] # Removes the key 'age'
my_dict.pop("profession", None) # Removes and returns, with a default if missing
my_dict.clear() # Clears all elements4. Dictionary Operations
4.1 Check if a Key Exists
"name" in my_dict # Returns True if 'name' is a key4.2 Get Dictionary Length
len(my_dict) # Returns the number of key-value pairs4.3 Copy a Dictionary
new_dict = my_dict.copy() # Creates a shallow copy of the dictionary4.4 Get All Keys or Values
all_keys = list(my_dict.keys())
all_values = list(my_dict.values())4.5 Update a Dictionary from Another
my_dict.update({"age": 26, "city": "Boston"}) # Updates and adds multiple keys at once5. Where You Use Dictionaries in This Course
Two places, and in both of them the dictionary is an argument to a pandas method rather than something you loop over.
5.1 Renaming columns (Day 2)
The keys are the old column names and the values are the new ones.
df = df.rename(columns={"Daily_AirTemp_Mean_C": "temp_c",
"Daily_Precip_Total_mm": "precip_mm"})5.2 Aggregating different columns differently (Day 5)
The keys are column names and the values name the summary you want from each.
summary = df.groupby("site").agg({"temperature_c": "mean",
"dissolved_oxygen": "max"})Compare that with .agg(["mean", "max"]), which applies the same two summaries to every column. The dictionary form is what lets you ask a different question of each column.