如何快速从键列表和列表值构建python字典?

时间:2019-05-25 18:31:58

标签: python list dictionary key-value enumerate

我必须列出

this.dialog.open(DialogComponent, {
  maxWidth: ''
});

我想从这两个列表中构建字典

labels = ['normal.']
percentages = [0.9936]

但是我遇到了错误:

d = {}
for k, v in enumerate(lables, percentages):
    d[k] = v

这可能是什么问题?

修改

然后当我收到字典时,我想执行此操作

TypeError: 'list' object cannot be interpreted as an integer

2 个答案:

答案 0 :(得分:2)

一种方法是将两个列表一起zip,并将压缩后的对象转换为字典。之后,您可以在dict.items()上进行迭代以创建列表

In [158]: labels = ['normal.'] 
     ...: percentages = [0.9936]                                                                                                                                                    

In [159]: previous_dict = dict(zip(labels,percentages))  
In [159]: previous_dict                                                                                                                              
Out[159]: {'normal.': 0.9936}

In [24]: result = [str(k) + ": " + str(v) for k, v in previous_dict.items()]                                                                                                        

In [25]: result                                                                                                                                                                     
Out[25]: ['normal.: 0.9936']

此外,enumerate为您提供了(index, element)类型的元组列表,您不能像这样传递两个迭代器,但是您可以再次zip两个迭代器并创建字典,然后代码如下。

对于Python 3.6+,我们还可以使用f-strings格式化字符串

In [167]: labels = ['normal.'] 
     ...: percentages = [0.9936]                                                                                                                                                    

In [169]: d = {} 
     ...: for k, v in zip(labels, percentages): 
     ...:     d[k] = v 

In [170]: d                                                                                                                                                                         
Out[170]: {'normal.': 0.9936}

In [30]: result = [f'{k}:{v}' for k, v in previous_dict.items()]                                                                                                                    

In [31]: result                                                                                                                                                                     
Out[31]: ['normal.:0.9936']

答案 1 :(得分:0)

这是您尝试使用列表理解的答案。要使第二步起作用,您需要使用.items()来访问键和值

labels = ['normal.']
percentages = [0.9936]

previous_dict = {k:v for k, v in zip(labels, percentages)}
# {'normal.': 0.9936}

result = [str(k) + ": " + str(v) for k, v in previous_dict.items()]
# ['normal.: 0.9936']