Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use a List as a dictionary key in Python 3?
Dictionaries are among the most powerful data structures in Python. They consist of key-value pairs and offer O(1) time complexity for accessing values. However, you cannot directly use lists as dictionary keys because lists are mutable and therefore not hashable.
Why Lists Cannot Be Dictionary Keys
Lists are mutable data types in Python, meaning their contents can be modified after creation. Dictionary keys must be hashable (immutable) because Python uses hash values to efficiently store and retrieve key-value pairs. If a list's contents change after being used as a key, its hash value would change, making it impossible to locate the associated value.
# This will raise a TypeError
my_dict = {}
my_list = [1, 2, 3]
try:
my_dict[my_list] = "This won't work"
except TypeError as e:
print(f"Error: {e}")
Error: unhashable type: 'list'
Method 1: Convert List to Tuple
The most common approach is converting the list to a tuple, which is immutable and hashable.
Syntax
tuple_key = tuple(list_name)
Example
my_dict = {}
numbers = [1, 2, 3]
tuple_key = tuple(numbers)
my_dict[tuple_key] = "Hello, World!"
print(my_dict)
print(f"Value: {my_dict[tuple_key]}")
{(1, 2, 3): 'Hello, World!'}
Value: Hello, World!
Method 2: Convert List to String
Another approach is converting the list to a string using the join() method.
Syntax
string_key = ''.join(str(element) for element in list_name)
Example
numbers = [1, 2, 3]
string_key = ''.join(str(e) for e in numbers)
my_dict = {string_key: 'concatenated values'}
print(my_dict)
print(f"Key: '{string_key}'")
{'123': 'concatenated values'}
Key: '123'
Method 3: Convert List to JSON String
Using the json.dumps() method preserves the list structure as a string representation.
Syntax
json_key = json.dumps(list_name)
Example
import json
numbers = [1, 2, 3]
json_key = json.dumps(numbers)
my_dict = {json_key: 'JSON formatted key'}
print(my_dict)
print(f"Key format: {json_key}")
{'[1, 2, 3]': 'JSON formatted key'}
Key format: [1, 2, 3]
Comparison of Methods
| Method | Preserves Structure | Memory Efficient | Best For |
|---|---|---|---|
| Tuple | Yes | Yes | Most use cases |
| String Join | No | Yes | Simple concatenation |
| JSON | Yes | Moderate | Complex nested structures |
Conclusion
Lists cannot be used directly as dictionary keys because they are mutable. Convert lists to immutable types like tuples, strings, or JSON strings to use them as keys. The tuple method is generally preferred as it preserves the original structure and is memory-efficient.
