如何使用List Comprehension构造以下字典?

时间:2016-12-23 10:03:38

标签: python python-3.x dictionary list-comprehension

您好我有以下词典:

vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}

weight = [23,445,56]

我想将第一个字典与权重列表相关联,如下所示,Word car的权重为23,因为键car的值为1,单词read的权重为56,因为是列表权重的3个位置,最后yellow的权重为2,因为445位于第二个位置列表,因此我想要的输出将是:

vocabulary_weight = {'yellow':445,'read':56,'car':23}

我试过了:

vocabulary_weight = {key: value for (vocabulary.keys(), weight[vocabulary.value()] ) 
                     in vocabulary}

但我得到了:

  File "<ipython-input-7-471237aaf624>", line 7
    vocabulary_weight = {key: value for (vocabulary.keys(), weight[vocabulary.value()] ) in vocabulary}
                                       ^
SyntaxError: can't assign to function call

所以我希望获得支持以获得所需的输出,感谢您的支持,

2 个答案:

答案 0 :(得分:2)

您可以迭代….addEventListener(eventType, …)这会为您提供键和值作为元组。使用vocabulary.items()解压缩并使用key, value作为列表的索引:

value - 1

答案 1 :(得分:1)

这应该有效:

vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}
weight = [23,445,56]

vocabulary_weight = {key : weight[int(vocabulary[key]) - 1] for key in vocabulary.keys()}