繁体   English   中英

如何使用列表理解来构造以下字典?

[英]how to construct the following dictionary, using List Comprehension?

您好,我有以下字典:

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

weight = [23,445,56]

我想联想与重量的列表中的第一部字典,如下所示,字重car23 ,因为关键的价值car是一个字的重量read56 ,因为是在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

因此,我想获得支持以实现所需的输出,谢谢您的支持,

您可以遍历vocabulary.items()这给您键和值作为元组。 使用key, value和使用value - 1作为列表的索引来解压:

>>> vocabulary =  {'car': 1, 'read': 3, 'yellow': 2}
>>> weight = [23,445,56]
>>> vocabulary_weight = {key: weight[value - 1] for key, value in vocabulary.items()}
>>> vocabulary_weight
{'car': 23, 'read': 56, 'yellow': 445}

这应该工作:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM