1. Creating Dictionaries
1.1 Empty Dictionary
= {} my_dict
1.2 Dictionary with Initial Values
= {"name": "Alice", "age": 30} my_dict
1.3 Dictionary with Mixed Data Types
= {"number": 42, "text": "hello", "list": [1, 2, 3], "flag": True} mixed_dict
1.4 Nested Dictionaries
= {
nested_dict "person1": {"name": "Alice", "age": 25},
"person2": {"name": "Bob", "age": 30}
}
2. Accessing Elements
2.1 Access by Key
print(my_dict["name"]) # Output: Alice
2.2 Safely Access Using .get()
print(my_dict.get("name")) # Output: Alice
print(my_dict.get("profession", "Unknown")) # Output: Unknown if not present
3. Modifying Dictionaries
3.1 Add or Update an Element
"profession"] = "Engineer" # Adds a new key or updates if exists my_dict[
3.2 Remove Elements
del my_dict["age"] # Removes the key 'age'
= my_dict.pop("profession", "No profession found") # Removes and returns
profession # Clears all elements my_dict.clear()
4. Dictionary Operations
4.1 Check if Key Exists
"name" in my_dict # Returns True if 'name' is a key
4.2 Iterate Through Keys, Values, or Items
for key in my_dict.keys():
print(key)
for value in my_dict.values():
print(value)
for key, value in my_dict.items():
print(f"{key}: {value}")
4.3 Dictionary Comprehensions
= {x: x**2 for x in range(5)} # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} squared
4.4 Merge Dictionaries
= {"name": "Alice", "age": 25}
dict1 = {"city": "New York", "age": 30}
dict2 = {**dict1, **dict2} # Python 3.5+ method merged
5. Common Dictionary Methods
5.1 Get Dictionary Length
len(my_dict) # Returns the number of key-value pairs
5.2 Copy a Dictionary
= my_dict.copy() # Creates a shallow copy of the dictionary new_dict
5.3 Get All Keys or Values
= list(my_dict.keys())
all_keys = list(my_dict.values()) all_values
5.4 Update Dictionary
"age": 26, "city": "Boston"}) # Updates and adds multiple keys my_dict.update({
5.5 Set Default Value for Key
"age", 29) # Sets 'age' to 29 if key is not present my_dict.setdefault(
6. Common Dictionary Pitfalls
6.1 Avoid Modifying a Dictionary While Iterating
# Incorrect
for key in my_dict:
if key.startswith('a'):
del my_dict[key]
# Correct (Using a copy of keys)
for key in list(my_dict.keys()):
if key.startswith('a'):
del my_dict[key]