Skip to Content
πŸŽ‰ Welcome to my notes πŸŽ‰
Python9. Dictionaries

πŸ“” Dictionaries in Python

Dictionaries are collections of key-value pairs. Keys must be unique and immutable.

dictionary.py
person = {"name": "Alice", "age": 25} print(person["name"]) # Output: Alice person["age"] = 26 # Update value print(person) # Output: {'name': 'Alice', 'age': 26}

🧩 Dictionary Operations

Dictionaries support various operations like adding, updating, and removing key-value pairs.

dict_operations.py
# Adding a new key-value pair person["city"] = "New York" print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'} # Removing a key-value pair del person["age"] print(person) # Output: {'name': 'Alice', 'city': 'New York'} # Checking if a key exists print("name" in person) # Output: True # Iterating through keys and values for key, value in person.items(): print(f"{key}: {value}") # Output: name: Alice # city: New York

πŸ› οΈ Dictionary Methods

dict_methods.py
# Dictionary methods person = {"name": "Alice", "age": 25} print(len(person)) # Output: 2 (number of key-value pairs) print("name" in person) # Output: True (check key existence) print(person.get("age")) # Output: 25 (get value safely by key) print(person.keys()) # Output: dict_keys(['name', 'age']) # Get all keys print(person.values()) # Output: dict_values(['Alice', 25]) # Get all values print(person.items()) # Output: dict_items([('name', 'Alice'), ('age', 25)]) # Get all key-value pairs # Merging dictionaries new_info = {"city": "New York", "age": 26} person.update(new_info) print(person) # Output: {'name': 'Alice', 'age': 26, 'city': 'New York'}
Last updated on