Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Can a Python Dictionary Have a List as a Value?

#1
Can a Python Dictionary Have a List as a Value?

5/5 – (1 vote)

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! ?



https://www.sickgaming.net/blog/2022/10/...s-a-value/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] List Comprehension in Python xSicKxBot 0 2,104 08-23-2023, 07:54 PM
Last Post: xSicKxBot
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,955 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] 5 Effective Methods to Sort a List of String Numbers Numerically in Python xSicKxBot 0 1,555 08-16-2023, 08:49 AM
Last Post: xSicKxBot
  [Tut] Sort a List, String, Tuple in Python (sort, sorted) xSicKxBot 0 1,695 08-15-2023, 02:08 PM
Last Post: xSicKxBot
  [Tut] Python Converting List of Strings to * [Ultimate Guide] xSicKxBot 0 1,606 05-02-2023, 01:17 PM
Last Post: xSicKxBot
  [Tut] Python List of Tuples to DataFrame ? xSicKxBot 0 1,511 04-22-2023, 06:10 AM
Last Post: xSicKxBot
  [Tut] Dictionary of Lists to DataFrame – Python Conversion xSicKxBot 0 1,377 04-17-2023, 03:46 AM
Last Post: xSicKxBot
  [Tut] Python List of Dicts to Pandas DataFrame xSicKxBot 0 1,530 04-11-2023, 04:15 AM
Last Post: xSicKxBot
  [Tut] How I Built an English Dictionary App with Django xSicKxBot 0 1,549 03-29-2023, 04:46 AM
Last Post: xSicKxBot
  [Tut] Python | Split String into List of Substrings xSicKxBot 0 1,439 12-11-2022, 12:17 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016