Definition
A dictionary in Python is a collection of key-value pairs, where each key is unique, and values can be of any data type. Dictionaries are mutable, unordered, and optimized for fast lookups, updates, and deletions.
Contents
Example
# Create a dictionary
person = {
"name": "Alice",
"age": 25,
"city": "New York"
}
# Access a value using a key
print(person["name"]) # Output: Alice
# Add a new key-value pair
person["profession"] = "Engineer"
# Update a value
person["age"] = 26
# Remove a key-value pair
del person["city"]
# Iterate through the dictionary
for key, value in person.items():
print(f"{key}: {value}")
Output
Alice
name: Alice
age: 26
profession: Engineer
Features
- Keys are Unique: Each dictionary key must be unique.
- Values can be Duplicates: Values do not need to be unique.
- Key Types: Keys must be immutable (e.g., strings, numbers, tuples).
- Unordered: In Python 3.7+, dictionaries maintain insertion order but are conceptually unordered.
- Built-in Methods: Rich set of methods like
get()
,keys()
,values()
, anditems()
for efficient data handling. - Dynamic Resizing: Automatically adjusts memory usage as the dictionary grows.
Advantages
- Fast Data Retrieval: Optimized for quick lookups by key.
- Flexibility: Supports various data types for values (e.g., strings, numbers, lists).
- Mutability: Can be modified after creation (add, update, or delete items).
- Dynamic Sizing: No need to predefine size; grows as needed.
- Readable Code: Key-value structure makes data organization intuitive.