How to use a List as a dictionary key in Python 3?


Dictionaries are among the most powerful data structures in Python programming languages. This is a data structure consisting of key-value pairs. It has several advantages; for example, accessing the values occurs in O(1) time complexity, it is memory efficient, easy to update, delete and iterate, and offers many built functions for quick operations.

Problem Associated When Lists Are Used Directly

We are focusing on this topic because there is a problem associated with when we try to make the lists as the key. Lists are mutable data types in Python. Hence, we can delete, update, and append values inside the list. So if we generate a hash function from the list and the items of the list change, then we can no longer find the hash function because the hash function is changed now.

Another potential issue is that different lists may have the same hash value. If two lists have the same sum of their values, their hash values will be the same. In such a case, if one of the lists is used as a key in the dictionary and another list with the same hash value is searched for, the dictionary may give an incorrect result.

Convert The List To Tuple

One way to make a list of the dictionary's keys is to convert it into a tuple and use this as the key. Note that this is the indirect way. Although the values are unchanged, the data type is no longer a list

Syntax

<variable name> = tuple(<list to convert into tuple>)

Here the tuple takes one parameter, which is the list's name.

Example

In the following code, we first created an empty dictionary named my_dict. Next, we created our list named my_list. We used the tuple method to convert the list into a Tuple object. We now used the Tuple object as the key as a string "hello, world!" as the value.

my_dict = {}
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
my_dict[my_tuple] = "Hello, World!"
print(my_dict)

Output

{(1, 2, 3): 'Hello, World!'}

Convert The List To a String

Another way is to convert the list into a string data type. The string is also an immutable data type; hence, we can use this as the dictionary's key.

Syntax

<variable name> = ''.join(str(e) for e in <name of the list>)

Here the statement takes the individual elements from the list and makes a string out of it. Join function concatenates sequence of string.

Example

In the following code, we first created a list named my_list. Next, we used the join method that creates a string of list elements. Since the string can be used as the dictionary key, we used this as te key of the dictionary my_list_str.

my_list = [1, 2, 3]
my_list_str = ''.join(str(e) for e in my_list)
my_dict = {my_list_str: 'value'}
print(my_dict)
print(my_dict[my_list_str])

Output

{'123': 'value'}
value

Convert The List To JSON

We can also use the JSON module and built-in functions to convert the list first to string using the dumps method and later use this as the dictionary's key.

Syntax

<name of variable< = json.dumps(<name of list<)

Here the dumbs method of the JSON library serializes Python objects into JSON formatted string. The dumps method takes the name of the string as the parameter

Example

In the following code, we first imported the JSON library. Next, we created a list named my_list. We used the dumps method to create a serialized object from the list. Now we used the serialized object as the dictionary key- my_dict.

import json
my_list = [1, 2, 3]
my_key = json.dumps(my_list)
my_dict = {my_key: 'value'}
print(my_dict)

Output

{'[1, 2, 3]': 'value'}

Conclusion

In this article, we learned how to use lists as the key of a dictionary in Python 3. We understood the difficulties we faced if we directly tried to make the lists as the keys in the Python dictionary. Therefore we first need to convert the list data type to tuples, strings, etc., which are immutable data types. We also learned how to use the JSON module to use lists as the dictionary key.

Updated on: 28-Jul-2023

72 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements