Dictionary in Python is a flexible and important data structure with several key properties and functions. Dictionary stores data in key-value pairs. It allows us to store multiple elements and manipulate data based on its keys and values.
Dictionary in Python
- Key-Value – Dictionary store data in key-value pairs. We can store multiple
key-value
pair elements, of different datatypes. - Unordered – Similar to Set, Dictionary is Python is also an unordered collection datatype. Dictionary elements (key-value) have no fixed order and do not maintain the sequence of its elements. From Python 3.8, dictionaries allowed to maintain the insertion order of its elements.
- Mutable – Dictionary is a mutable collection datatype. It means we can perform add (append), update (change), delete (remove) operations on the dictionary objects.
- Indexed by keys: Dictionary elements are indexed by keys. As a key-pair element, keys are indexed and values are stored for those keys (index). We can use keys to access its corresponding value.
- Immutable keys – Dictionary element keys must be unique and of immutable types (e.g., strings, numbers, and tuples). Key values can be of any datatype. Mutable datatypes like lists, sets or dictionaries cannot be used as keys.
- Dynamic size – Dictionary in Python are mutable datatype. We can perform add, update or remove operations on dictionary. Size of dictionary (number of elements in dictionary) can increase or decrease based on these operations.
- Fast lookup – Dictionary elements are key-value pair and indexed based on keys. This feature helps to provide fast searching, insertion and deletion operation within the dictionary. Because of key based indexing (hashing technique) these operations can be performed in O(1) time complexity.
- Keys, values and items iteration – Dictionary allows to traverse over all the elements. We can iterate over keys, value and items (key-value) pair of dictionaries.
- Nested Dictionary – Dictionary allows another dictionary to be stored as a value. Another dictionary cannot be used as a key.
- From Python version 3.7 and later, dictionaries maintain insertion order.