如何从键列表和列表值快速构建 python 字典?
How to build a python dictionary from a list of keys and a list values, quickly?
我必须列出
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
这里有什么问题吗?
编辑
然后拿到dict后,我要执行这个操作
result = [str(k) + ": " + str(v) for k, v in previous_dict]
一种方法是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']
这是您尝试做的使用列表理解的答案。要使第二步正常工作,您需要使用 .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']
我必须列出
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
这里有什么问题吗?
编辑
然后拿到dict后,我要执行这个操作
result = [str(k) + ": " + str(v) for k, v in previous_dict]
一种方法是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']
这是您尝试做的使用列表理解的答案。要使第二步正常工作,您需要使用 .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']