python - 将 2 元素列表转换为字典

标签 python python-2.7 dictionary

我知道这里回答的关于 dict(list) 的问题很少,即

l = [['a',1] ['b',2]]

然后执行 dict(l) 然后我们得到:

{'a': 1, 'b': 2}

但是如何制作一个包含 2 个元素的列表

l = ['a',1]

变成字典如:

{'a':1}

使用 dict 函数?

最佳答案

dict 需要一个包含两项的可迭代对象,因此您需要将 l 放入列表中:

>>> l = ['a',1]
>>> dict([l])
{'a': 1}
>>>

请注意,您还可以使用元组:

>>> l = ['a',1]
>>> dict((l,))
{'a': 1}
>>>

关于python - 将 2 元素列表转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27926747/

相关文章:

python - 如何在python脚本中设置环境变量

python - 在 Jupyter 中切换内核

python - Python 3 和 matplotlib 中的 Unicode 绘图标记

python - 在 Python 中动态创建嵌套字典

python - 创建唯一列表 : comparing dict objects

python - 在 Python 中操作数据结构

python - 某个 wheel (.whl) 包的依赖项是什么?

python - 导入skimage导入数据报错,过滤器

python - 我将如何通过 python 脚本运行 lsvirtualenv 或任何其他 virtualenvwrapper 函数?

python - 使用 write_shp 在 NetworkX 中写入 shapefile