A dictionary in Python is an unordered, mutable, and key-value paired data structure. It allows you to store and retrieve values using unique keys.
my_dict = {
"name": "Alice",
"age": 25,
"city": "New York"
}
"name"
, "age"
, "city"
) must be unique and immutable (strings, numbers, or tuples)."Alice"
, 25
, "New York"
) can be any data type.Feature | Dictionary (dict ) |
List (list ) |
---|---|---|
Structure | Key-value pairs | Ordered collection of elements |
Access Elements | my_dict["name"] (via keys) |
my_list[0] (via index) |
Mutability | Mutable (can update values) | Mutable (can add/remove elements) |
Ordering | Maintains order (since Python 3.7+) | Ordered |
Duplicates | Keys must be unique | Can have duplicate elements |
Use Case | When data is labeled (e.g., user info) | When data is sequential (e.g., numbers, items in a queue) |
# List Example (Indexed Access)
my_list = ["Alice", 25, "New York"]
print(my_list[0]) # Output: Alice
# Dictionary Example (Key-Based Access)
my_dict = {"name": "Alice", "age": 25, "city": "New York"}
print(my_dict["name"]) # Output: Alice
* Dictionaries are best for labeled data (e.g., a database record).
* Lists are best for ordered collections (e.g., a list of items in a shopping cart).