Can a Python Dictionary Have a List as a Value?

Question

πŸ’¬ Question: Can you use lists as values of a dictionary in Python?

This short article will answer your question. So, let’s get started right away with the answer:

Answer

You can use Python lists as dictionary values. In fact, you can use arbitrary Python objects as dictionary values and all hashable objects as dictionary keys. You can define a list [1, 2] as a dict value either with dict[key] = [1, 2] or with d = {key: [1, 2]}.

Here’s a concrete example showing how to create a dictionary friends where each dictionary value is in fact a list of friends:

friends = {'Alice': ['Bob', 'Carl'],
           'Bob': ['Alice'],
           'Carl': []}


print('Alice friends: ', friends['Alice'])
# Alice friends:  ['Bob', 'Carl']

print('Bob friends: ', friends['Bob'])
# Bob friends:  ['Alice']

print('Carl friends: ', friends['Carl'])
# Carl friends:  []

Note that you can also assign lists as values of specific keys by using the dictionary assignment operation like so:

friends = dict()
friends['Alice'] = ['Bob', 'Carl']
friends['Bob'] = ['Alice']
friends['Carl'] = []


print('Alice friends: ', friends['Alice'])
# Alice friends:  ['Bob', 'Carl']

print('Bob friends: ', friends['Bob'])
# Bob friends:  ['Alice']

print('Carl friends: ', friends['Carl'])
# Carl friends:  []

Can I Use Lists as Dict Keys?

You cannot use lists as dictionary keys because lists are mutable and therefore not hashable. As dictionaries are built on hash tables, all keys must be hashable or Python raises an error message.

Here’s an example:

d = dict()
my_list = [1, 2, 3]
d[my_list] = 'abc'

This leads to the following error message:

Traceback (most recent call last):
  File "C:\Users\xcent\Desktop\code.py", line 3, in <module>
    d[my_list] = 'abc'
TypeError: unhashable type: 'list'

To fix this, convert the list to a Python tuple and use the Python tuple as a dictionary key. Python tuples are immutable and hashable and, therefore, can be used as set elements or dictionary keys.

Here’s the same example after converting the list to a tuple—it works! πŸŽ‰

d = dict()
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
d[my_tuple] = 'abc'

Before you go, maybe you want to join our free email academy of ambitious learners like you? The goal is to become 1% better every single day (as a coder). We also have cheat sheets! πŸ‘‡