Open In App

How to use a List as a key of a Dictionary in Python 3?

Last Updated : 17 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

In Python, we use dictionaries to check if an item is present or not . Dictionaries use key:value pair to search if a key is present or not and if the key is present what is its value . We can use integer, string, tuples as dictionary keys but cannot use list as a key of it . The reason is explained below .

How does Python Dictionaries search their keys 
 

If the Python dictionaries just iterate over their keys to check if the given keys are present or not it would take O(N) time. But python dictionaries take O(1) to check if the key is present or not. So, how dictionaries search the key, for every key it generates a hash value for the key and by this hash value, it can track its elements.

Problems if lists were used as a key of dictionaries 
 

Lists are mutable objects which means that we can change values inside a list append or delete values of the list . So if a hash function is generated from a list and then the items of the lists changed the dictionary will generate a new hash value for this list and could not find it.

For example, If the list is a = [1, 2, 3, 4, 5] and supposes hash of a list is the sum of values inside the list. So hash(a) = 15. Now we append 6 to a . So a = [1, 2, 3, 4, 5, 6] hash(a) = 21. So hash value of a changed. Therefore it can not be found inside the dictionary.

Another problem is different lists with the same hash value. If b = [5, 5, 5] hash(b) = 15. So if a (From the above example with the same hash value) is present is inside the dictionary, and if we search for b. Then the dictionary may give us the wrong result.

How to deal with this 

We can change the list into immutable objects like string or tuple and then can use it as a key.  Below is the implementation of the approach.
 




# Declaring a dictionary
d = {} 
  
# This is the list which we are 
# trying to use as a key to
# the dictionary
a =[1, 2, 3, 4, 5]
  
# converting the list a to a string
p = str(a)
d[p]= 1
  
# converting the list a to a tuple
q = tuple(a) 
d[q]= 1
  
for key, value in d.items():
    print(key, ':', value)


 
Output:

[1, 2, 3, 4, 5] : 1
(1, 2, 3, 4, 5) : 1

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads