Prerequisites:
The dictionary can be maintained in heap either based on the key or on the value. The conventions to be maintained are listed below:
- The key-value pair at index āiā is considered to be the parent of key-value pair at the indices 2k+1 and 2k+2.
- For a min-heap, the parent key/value must be smaller than its children.
- For a max-heap, the parent key/value must be larger than its children.
Examples:
Normal dictionary : {11:2, 0:4, 5:9, 22:7}
Heap based on keys of the dictionary : {0: 4, 1: 1, 5: 9, 22: 7, 11: 2}
Heap based on values of the dictionary : {11: 2, 0: 4, 5: 9, 22: 7}
This article shows how to maintain a dictionary in a min-heap using the heapq module.
Normal dictionary as a heap
The normal dictionary with integers/strings as the key can be maintained in a heap structure with the help of the heapq module. But this module expects a list to be passed. So the approach used here is :
- Convert the key-value pairs into a list of tuples.
- Pass the list of tuples to heapify() function.
- Convert the resulting list into a dictionary again.
Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only.
Example 1: Based on the Key for integers
Consider a dictionary where the keys are positive integers and the values are their squares. Now, this should be maintained in a heap.
Python3
# import modules import heapq as hq Ā
# dictionary to be heapified dict_1 = { 11 : 121 , 2 : 4 , 5 : 25 , 3 : 9 } Ā
# convert dictionary to list of tuples di = list (dict_1.items()) Ā
print ( "dictionary into list :" , di) Ā
# converting into heap hq.heapify(di) Ā
print ( "Heapified list of tuples :" , di) Ā
# converting heap to dictionary di = dict (di) Ā
print ( "Dictionary as heap :" , di) |
dictionary into list : [(11, 121), (2, 4), (5, 25), (3, 9)] Heapified list of tuples : [(2, 4), (3, 9), (5, 25), (11, 121)] Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121}
Example 2: Based on key for StringĀ
Consider a dictionary which has a combination of alphabets as key and their numbering as values. For example: āabcā : 123. This has to be maintained in heap.Ā
Python3
# import modules import heapq as hq Ā
# dictionary to be heapified dict_1 = { "yz" : 2526 , "ab" : 12 , "cd" : 34 , "ij" : 910 , "fg" : 67 } Ā
# convert dictionary to list of tuples di = list (dict_1.items()) Ā
print ( "dictionary into list :" , di) Ā
# converting into heap hq.heapify(di) Ā
print ( "Heapified list of tuples :" , di) Ā
# converting heap to dictionary di = dict (di) Ā
print ( "Dictionary as heap :" , di) |
Output:
dictionary into list : [(āyzā, 2526), (āabā, 12), (ācdā, 34), (āijā, 910), (āfgā, 67)]Ā
Heapified list of tuples : [(āabā, 12), (āfgā, 67), (ācdā, 34), (āijā, 910), (āyzā, 2526)]Ā
Dictionary as heap : {āabā: 12, āfgā: 67, ācdā: 34, āijā: 910, āyzā: 2526}
Example 3: Based on the value
The approach slightly differs here. The steps to be carried out are:
- Extract the values in the dictionary and append to a list.
- Pass the list to heapify().
- Based on the heapified list values, reconstruct a new dictionary from the original one by iterating through it.
Here only the values satisfy the heap property and not necessarily the keys.
Example:
Python3
# import the module import heapq as hq Ā
# dictionary to be heapified li_dict = { 11 : 121 , 2 : 4 , 5 : 25 , 3 : 9 } Ā
# List to hold values from dictionary heap_dict = [] Ā
# extract the values from dictionary for i in li_dict.values(): Ā Ā Ā Ā heap_dict.append(i) Ā Ā Ā Ā Ā # heapify the values hq.heapify(heap_dict)Ā Ā print ( "Values of the dict after heapification :" ,heap_dict) Ā
# list to hold final heapified dictionary new_dict = [] Ā
# mapping and reconstructing final dictionary for i in range ( 0 , len (heap_dict)): Ā Ā Ā Ā Ā Ā Ā Ā Ā # Iterating the oringinal dictionary Ā Ā Ā Ā for k,v in li_dict.items(): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if v = = heap_dict[i] and (k,v) not in new_dict: Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā new_dict.append((k,v)) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā new_dict = dict (new_dict) Ā
print ( "Final dictionary :" ,new_dict) |
Values of the dict after heapification : [4, 9, 25, 121] Final dictionary : {2: 4, 3: 9, 5: 25, 11: 121}
List of dictionaries as a heap
The examples seen above are based on a single dictionary. Consider a list of dictionaries which has to be maintained as a heap. The approach used is:Ā
- Convert each dictionary into a tuple using list comprehension.
- Pass the list to heapify().
- Convert the resulting list of heapified tuples into the dictionary.
Note: The heapify() on tuples considers the first element in the tuple for the process. Thus, by default, the dictionaries are maintained in heap, based on the key only.
Example :Ā
Python3
# import modules import heapq as hq Ā
# list of dictionaries li_dict = [{ 11 : 121 },{ 2 : 4 },{ 5 : 25 },{ 3 : 9 }] Ā
#temporary list to hold tuple of key-value pairs heap_dict = [] Ā
# convert each dict to tuple heap_dict = [(k,v) for i in li_dict for k,v in i.items() ] Ā
print ( "After extraction :" ,heap_dict) Ā
# heapify the list of tuples hq.heapify(heap_dict)Ā Ā Ā
print ( "Heapified key-value pairs :" ,heap_dict) Ā
# reconvert to dictionary final = dict (heap_dict) print ( "Heapified dictionaries :" ,final) |
After extraction : [(11, 121), (2, 4), (5, 25), (3, 9)] Heapified key-value pairs : [(2, 4), (3, 9), (5, 25), (11, 121)] Heapified dictionaries : {2: 4, 3: 9, 5: 25, 11: 121}
Nested dictionaries
In the case of nested dictionaries, the task takes more steps to maintain the dictionary in heap. If the dictionary has to be maintained based on the key in a inner dictionary, then the following approach can be used.
- Convert the dictionary into list of tuples where the key of the outer dictionary is tuple[0] and the inner dictionary is tuple[1].
- Extract the values of the key in inner dictionaries into a list.
- Apply heapify() on that list.
- Re-construct a new dictionary by ordering them based on the heapified results.
For example, consider a record of employees as a nested dictionary. The record appears as given below:Ā
{
Ā Ā āemp01ā:{
Ā Ā Ā Ā ānameā:āKateā,
Ā Ā Ā Ā āageā:22,
Ā Ā Ā Ā ādesignationā: āAnalystā,
Ā Ā Ā Ā āSalaryā:30000
Ā Ā },
Ā Ā āemp02ā:{
Ā Ā Ā Ā ānameā:āRinaā,
Ā Ā Ā Ā āageā:20,
Ā Ā Ā Ā ādesignationā:āProgrammerā,
Ā Ā Ā Ā āSalaryā:25000
Ā Ā },
Ā Ā āemp03ā:{
Ā Ā Ā Ā ānameā:āVikasā,
Ā Ā Ā Ā āageā:42,
Ā Ā Ā Ā ādesignationā:āManagerā,
Ā Ā Ā Ā āSalaryā:35000
Ā Ā },
Ā Ā āemp04ā:{
Ā Ā Ā Ā ānameā:āmanishā,
Ā Ā Ā Ā āageā:42,
Ā Ā Ā Ā ādesignationā:āManagerā,
Ā Ā Ā Ā āSalaryā:15000
Ā Ā }
}
Now let us maintain this in a min-heap based on the salary values. Thus, the employee with minimum salary appears as the first record. For better readability and understanding we can split the code into functions.
Step 1: Ā Define the function to convert the dictionary into a listĀ
Python3
def get_list(d): Ā Ā Ā Ā Ā Ā Ā Ā Ā list_li = list (d.items()) Ā Ā Ā Ā Ā Ā Ā Ā Ā print ( "Dictionary as list" ,list_li, "\n" ) Ā Ā Ā Ā Ā Ā Ā Ā Ā return (list_li) |
Ā
Step 2: Define the function that performs heapification. Takes the list of tuples as parameter.Ā
Python3
def convert_heap(list_li): Ā Ā Ā Ā Ā Ā Ā Ā Ā # list to hold salary values Ā Ā Ā Ā sal_li = [] Ā
Ā Ā Ā Ā # extract salary values Ā Ā Ā Ā for i in range ( 0 , len (list_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā sal_li.append(list_li[i][ 1 ][ 'Salary' ]) Ā
Ā Ā Ā Ā print ( "Before heapify :" ,sal_li, "\n" ) Ā
Ā Ā Ā Ā # heapify the salary values Ā Ā Ā Ā hq.heapify(sal_li) Ā
Ā Ā Ā Ā print ( "After salary :" ,sal_li, "\n" ) Ā
Ā Ā Ā Ā # list to hold the final dictionary as heap Ā Ā Ā Ā final = [] Ā
Ā Ā Ā Ā # reconstruction of dictionary as heap Ā Ā Ā Ā # yields a list of tuples of key-value pairs Ā Ā Ā Ā for i in range ( 0 , len (sal_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for j in range ( 0 , len (sal_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if list_li[j][ 1 ][ 'Salary' ] = = sal_li[i]: Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā final.append(list_li[j]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # list of tuples to dictionary Ā Ā Ā Ā final = dict (final) Ā Ā Ā Ā Ā Ā Ā Ā return final |
Step 3: Define the dictionary and call the functions appropriately.
Python3
nested_dict = { Ā Ā Ā Ā "emp01" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Kate" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 22 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Analyst" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 30000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp02" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Rina" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 20 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Programmer" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 25000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp03" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Vikas" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 42 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Manager" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 35000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp04" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "manish" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 42 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Manager" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 15000 Ā Ā Ā Ā } } Ā
list_li = get_list(nested_dict) Ā
final = convert_heap(list_li) Ā
print ( "Dictionary as heap :" ,final) |
Now putting all the code together we get a nested dictionary maintained in heap, based on the values of the salary.
Python3
import heapq as hq Ā
def get_list(d): Ā Ā Ā Ā Ā Ā Ā Ā Ā list_li = list (d.items()) Ā Ā Ā Ā Ā Ā Ā Ā Ā print ( "Dictionary as list" ,list_li, "\n" ) Ā Ā Ā Ā Ā Ā Ā Ā Ā return (list_li) Ā Ā Ā def convert_heap(list_li): Ā Ā Ā Ā Ā Ā Ā Ā Ā # list to hold salary values Ā Ā Ā Ā sal_li = [] Ā
Ā Ā Ā Ā # extract salary values Ā Ā Ā Ā for i in range ( 0 , len (list_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā sal_li.append(list_li[i][ 1 ][ 'Salary' ]) Ā
Ā Ā Ā Ā print ( "Before heapify :" ,sal_li, "\n" ) Ā
Ā Ā Ā Ā # heapify the salary values Ā Ā Ā Ā hq.heapify(sal_li) Ā
Ā Ā Ā Ā print ( "After heapify :" ,sal_li, "\n" ) Ā
Ā Ā Ā Ā # list to hold the final dictionary as heap Ā Ā Ā Ā final = [] Ā
Ā Ā Ā Ā # reconstruction of dictionary as heap Ā Ā Ā Ā # yields a list of tuples of key-value pairs Ā Ā Ā Ā for i in range ( 0 , len (sal_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā for j in range ( 0 , len (sal_li)): Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā if list_li[j][ 1 ][ 'Salary' ] = = sal_li[i]: Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā final.append(list_li[j]) Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā Ā # list of tuples to dictionary Ā Ā Ā Ā final = dict (final) Ā Ā Ā Ā Ā Ā Ā Ā return final Ā Ā Ā nested_dict = { Ā Ā Ā Ā "emp01" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Kate" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 22 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Analyst" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 30000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp02" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Rina" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 20 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Programmer" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 25000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp03" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "Vikas" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 42 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Manager" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 35000 Ā Ā Ā Ā }, Ā Ā Ā Ā "emp04" :{ Ā Ā Ā Ā Ā Ā Ā Ā "name" : "manish" , Ā Ā Ā Ā Ā Ā Ā Ā "age" : 42 , Ā Ā Ā Ā Ā Ā Ā Ā "designation" : "Manager" , Ā Ā Ā Ā Ā Ā Ā Ā "Salary" : 15000 Ā Ā Ā Ā } } Ā
list_li = get_list(nested_dict) Ā
final = convert_heap(list_li) Ā
print ( "Dictionary as heap :" ,final) |
Output
Dictionary as list [(āemp01ā², {ānameā: āKateā, āageā: 22, ādesignationā: āAnalystā, āSalaryā: 30000}), (āemp02ā², {ānameā: āRinaā, āageā: 20, ādesignationā: āProgrammerā, āSalaryā: 25000}), (āemp03ā², {ānameā: āVikasā, āageā: 42, ādesignationā: āManagerā, āSalaryā: 35000}), (āemp04ā², {ānameā: āmanishā, āageā: 42, ādesignationā: āManagerā, āSalaryā: 15000})]
Ā Before heapify : [30000, 25000, 35000, 15000]Ā
Ā After heapify : [15000, 25000, 35000, 30000]Ā
Dictionary as heap : {āemp04ā²: {ānameā: āmanishā, āageā: 42, ādesignationā: āManagerā, āSalaryā: 15000}, āemp02ā²: {ānameā: āRinaā, āageā: 20, ādesignationā: āProgrammerā, āSalaryā: 25000}, āemp03ā²: {ānameā: āVikasā, āageā: 42, ādesignationā: āManagerā, āSalaryā: 35000}, āemp01ā²: {ānameā: āKateā, āageā: 22, ādesignationā: āAnalystā, āSalaryā: 30000}}
Insertion in dictionary maintained as a heap
The insertion of new values can be done directly using heappush() method in the heapq module. Its syntax is as follows.
heapq . heappush ( list , new_value )
Now the list of tuples along with a new tuple can be passed to this function to add the new-key value pair.
Example :
Python3
import heapq as hq Ā
# list of dictionaries li_dict = [{ 11 : 121 },{ 2 : 4 },{ 5 : 25 },{ 3 : 9 }] Ā
# list to hold tuples heap_dict = [] Ā
# convert each dict to tuple of (key,value) heap_dict = [(k,v) for i in li_dict for k,v in i.items() ] Ā
print ( "List of tuples :" ,heap_dict) Ā
# applying heapify() hq.heapify(heap_dict)Ā Ā Ā
print ( "After heapification :" ,heap_dict) Ā
# reconvert to dict final = dict (heap_dict) Ā
print ( "Dictionary as heap :" ,final) Ā
# add new value (1,1) hq.heappush(heap_dict,( 1 , 1 )) Ā
print ( "After insertion & heapification" ,heap_dict) Ā
#reconvert the result final = dict (heap_dict) Ā
print ( "New dictionary :" ,final) |
Output:
List of tuples : [(11, 121), (2, 4), (5, 25), (3, 9)]Ā
After heapification : [(2, 4), (3, 9), (5, 25), (11, 121)]Ā
Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121}Ā
After insertion & heapification [(1, 1), (2, 4), (5, 25), (11, 121), (3, 9)]Ā
New dictionary : {1: 1, 2: 4, 5: 25, 11: 121, 3: 9}
Another method that can be done is to have a function that heapify the dictionary and calling it after updating the dictionary.Ā
Example :
Python3
import heapq as hq Ā
def heapify_dict(d): Ā Ā Ā Ā Ā Ā Ā Ā Ā # convert to list of tuples Ā Ā Ā Ā li = list (dict1.items()) Ā Ā Ā Ā Ā Ā Ā Ā Ā hq.heapify(li) Ā Ā Ā Ā Ā Ā Ā Ā Ā li = dict (li) Ā Ā Ā Ā Ā Ā Ā Ā Ā print ( "Dictionary as heap :" ,li) Ā Ā Ā Ā Ā dict1 = { 11 : 121 , 2 : 4 , 5 : 25 , 3 : 9 } Ā
print ( "Before adding new values" ) heapify_dict(dict1) Ā
# add new values to dictionary dict1[ 4 ] = 16 dict1[ 1 ] = 1 Ā
print ( "Updated dictionary :" ,dict1) Ā
print ( "After adding new values" ) heapify_dict(dict1) |
Before adding new values Dictionary as heap : {2: 4, 3: 9, 5: 25, 11: 121} Updated dictionary : {11: 121, 2: 4, 5: 25, 3: 9, 4: 16, 1: 1} After adding new values Dictionary as heap : {1: 1, 2: 4, 5: 25, 3: 9, 4: 16, 11: 121}
Ā