Data Structures in Python - Episode 5: Dictionaries
Introduction
Dictionaries are key-value pairs used to store and retrieve data efficiently. They are unordered collections, where each key must be unique and immutable.
Example 1: Creating a Dictionary
# Creating a dictionary
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict)
{'name': 'Alice', 'age': 25, 'city': 'New York'}
Example 2: Accessing and Modifying Data
# Accessing a value
print(my_dict["name"])
# Modifying a value
my_dict["age"] = 26
print(my_dict)
Alice
{'name': 'Alice', 'age': 26, 'city': 'New York'}
{'name': 'Alice', 'age': 26, 'city': 'New York'}
Example 3: Useful Dictionary Methods
# Some common methods
print(my_dict.keys())
print(my_dict.values())
print(my_dict.items())
dict_keys(['name', 'age', 'city'])
dict_values(['Alice', 26, 'New York'])
dict_items([('name', 'Alice'), ('age', 26), ('city', 'New York')])
dict_values(['Alice', 26, 'New York'])
dict_items([('name', 'Alice'), ('age', 26), ('city', 'New York')])
Quick Recap
Operation | Description |
---|---|
dict[key] |
Access the value associated with a key |
dict.keys() |
Returns all keys |
dict.values() |
Returns all values |
dict.items() |
Returns all key-value pairs |
Important Notes
Tip: Keys must be unique and immutable (e.g., strings, numbers, tuples).
Warning: Attempting to access a non-existent key will raise a
Warning: Attempting to access a non-existent key will raise a
KeyError
.
Comments
Post a Comment