Making two lists into a dictionary error: unhashable type: 'list'

Question:

Hi I’m trying to make two lists into a dictionary as keys and values, but I got error

TypeError                                 Traceback (most recent call last)
<ipython-input-535-a88b451e7100> in <module>()
      1 #
      2 DN = {key: value for key, value in zip(NiW, NiV)}
----> 3 DY = {key: value for key, value in zip(YiW, YiV)}
      4 D = dict(DN, **DY)
TypeError: unhashable type: 'list'

I did some research it seems like it’s the outer list of the nested list caused this error but I’m unsure

The Data

YiW
[['africa', 'trip'],
['asia', 'travel'],
['europe', 'holiday']]
 
YiV
[[array([-0.34219775,  0.61445   ,  0.19807251],
array([ 1.8527551 ,  2.4294894 ,  0.3062766],
[array([-0.34219775,  0.61445   ,  0.19807251,  0.15776388],
array([ 1.8527551 ,  2.4294894 ,  0.3062766],
[array([-0.34219775,  0.61445   ,  0.19807251,  0.15776388],
array([ 1.8527551 ,  2.4294894 ,  0.3062766]]

Idea output:

{'africa':array([-0.34219775,  0.61445   ,  0.19807251],
'trip':array([-0.34219775,  0.61445   ,  0.19807251,  0.15776388]}etc..

I tried many ways to remove outer list: Flatten list of lists, How do I concatenate (join) items in a list to a single string?, https://stackoverflow.com/questions/16359052; but I can’t make it work. How can I fix the code?

Asked By: Osca

||

Answers:

You seem to want both location and type to be independently mapped to the same values. You’d need to make the dict comprehension use nested loops to pull this off, since each value in YiW is a list of keys to make, not a single key. Simple approach:

DY = {key: value for keys, value in zip(YiW, YiV) for key in keys}

Note that this will drop data if any key appears more than once (so if YiW contains both ["africa", "trip"] and later ["asia", "trip"], you’ll only map "trip" to the value that paired with ["asia", "trip"]). If that’s not what you want, you’ll need to be more specific in the desired behavior.

Answered By: ShadowRanger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.