TreeMap is a data structure that stores key-value pairs in a sorted order based on the keys. In Python, there is no direct built-in implementation of a TreeMap, but the sortedcontainers module provides a SortedDict class that works similarly to a TreeMap.
TreeMap is implemented using a balanced binary search tree (such as Red-Black Tree or AVL Tree), ensuring that the elements are stored in a sorted order and can be efficiently searched, inserted, or deleted.
TreeMap in Python
To create a TreeMap (SortedDict) in Python, we first need to install sorted containers library. To install the library, we need the following command:
pip install sortedcontainers
After installing sortedcontainers, we can import SortedDict from it.
Below is the implementation of TreeMap(or Sorted Dictionary):
from sortedcontainers import SortedDict
# Creating a dictionary
d = SortedDict({2:"GfG", 1:"Geeks", 3:"POTD"})
print(d)
# Insertion in dictionary
d[-1] = "Hello"
d[0] = "World"
print("After Insertion:", d)
# Deletion in dictionary
del d[-1]
d.pop(3)
print("After Deletion:", d)
Output
SortedDict({1: 'Geeks', 2: 'GfG', 3: 'POTD'})
After Insertion: SortedDict({-1: 'Hello', 0: 'World', 1: 'Geeks', 2: 'GfG', 3: 'POTD'})
After Deletion: SortedDict({0: 'World', 1: 'Geeks', 2: 'GfG'})
Alternate Implementation:
If you cannot install sortedcontainers library, then you can also create a TreeMap in Python using a Dictionary and sort it on the basis of keys.
# Creating a dictionary
d = {2:"GfG", 1:"Geeks", 3:"POTD"}
# Sorting by keys
sorted_d = dict(sorted(d.items()))
print(sorted_d)
Output
{1: 'Geeks', 2: 'GfG', 3: 'POTD'}
Related Articles: