【问题标题】:Making two lists into a dictionary error: unhashable type: 'list'将两个列表制作成字典错误:不可散列类型:'list'
【发布时间】:2018-08-30 03:16:50
【问题描述】:

您好,我正在尝试将两个列表作为键和值放入字典中,但出现错误

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'

我做了一些研究,似乎是嵌套列表的外部列表导致了这个错误,但我不确定

数据

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]]

创意输出:

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

我尝试了很多方法来删除外部列表: flatten-list-of-lists

concatenate-item-in-list-to-strings

how-to-convert-nested-list-into-dictionary-in-python-where-lst00-is-the-key 但是他们在这种情况下不工作,有人可以帮忙吗?提前谢谢你!

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

    您似乎希望位置和类型都独立映射到相同的值。您需要使 dict 理解使用嵌套循环来实现这一点,因为 YiW 中的每个值都是要创建的键的 list,而不是单个键。简单的方法:

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

    请注意,如果任何键出现多次,这将删除数据(因此,如果 YiW 包含 ["africa", "trip"] 和更高版本的 ["asia", "trip"],则您只会将 "trip" 映射到与 ["asia", "trip"] 配对的值)。如果这不是您想要的,您需要更具体地说明所需的行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-27
      • 2012-01-21
      • 1970-01-01
      • 2016-01-11
      • 2019-01-07
      • 1970-01-01
      • 2021-02-22
      • 2015-04-01
      相关资源
      最近更新 更多