Dict
dict is a pre-defined class in Python, categorized as a Dict Category Data Type (a type of collection).
- To store data in the form of (Key, Value) pairs, where keys are unique and immutable, and Values can be unique or duplicate and can be of any type (mutable or immutable).
# Creating an empty Dict
dictobjname = {} # or
dictobjname = dict()
# Non-Empty Dictionary
dictobjname = {Key1: Val1, Key2: Val2, ..., KeyN: ValN}
# Adding Key-Value Pairs to an Empty Dictionary
dictobjname[Key1] = Val1
dictobjname[Key2] = Val2
- Insertion Order: Since Python 3.7+, dictionaries maintain insertion order (elements are displayed in the order they were added).
- No Indexing/Slicing: Dictionaries do not support indexing or slicing because they are not sequence-based; access is via keys.\
Mutability:
- The dictionary object is mutable (you can add, update, or remove key-value pairs).
- Keys must be immutable (e.g., int, str, tuple).
- Values can be mutable (e.g., lists, dictionaries) or immutable.
- Key Uniqueness: Keys must be unique; duplicate keys are not allowed (the last value for a key overwrites previous ones).
- Value Flexibility: Values can be duplicates and of any type
Use Cases:
Dictionaries are widely used for.
- Storing configuration settings (e.g., {"host": "localhost", "port": 8080}).
- Mapping relationships (e.g., student IDs to names).
- Counting occurrences (e.g., word frequency in a text).