TypeError with List Comprehension When Trying to Create a Dictionary from Tuples

Question:

I’m encountering a TypeError: unhashable type: ‘list’ while attempting to create a dictionary from tuples using list comprehension, and I can’t figure out why this error occurs as I’m not using any lists in my code.

Here’s the snippet of code that’s causing the issue:

data = (
    'abcdefg',
    (10, 20, 30, 40, 50),
    (55, 81, 33, 44)
)

# I want to convert this into a dictionary where keys are indices and values are lengths of each element in 'data'
# The expected dictionary should be {0: 7, 1: 5, 2: 4}

# My initial approach without list comprehension worked fine:
# lens = dict()
# for el in enumerate(data):
#     lens[el[0]] = len(el[1])

# But when I try to use list comprehension, I get an error
lens = {[el[0]]: len(el[1]) for el in enumerate(data)}

print(lens)

I expected the list comprehension to work similarly to the loop, but it doesn’t. Could someone explain why this TypeError is occurring and how to correctly use list comprehension in this context?

Asked By: neznajut

||

Answers:

I suggest this:

data = (
    'abcdefg',
    (10, 20, 30, 40, 50),
    (55,81, 33, 44)
)

# TODO from this:

# lens = dict()
#
# for el in enumerate(data):
#     lens[el[0]] = len(el[1])

# TODO to this
lens = {el[0]: len(el[1]) for el in enumerate(data)}

print(lens)

[el[0]] generates a list. You cannot store list as a key in python dictionaries. Even if list is of only one element.
What you need is el[0] as your key.

Output:

{0: 7, 1: 5, 2: 4}
Answered By: Shrirang Mahajan