python - 将元组元素转换为字典

标签 python python-3.x

我需要转换这样的结构:

(1, 2, 3, 4, 5, 6)

像这样的字典:

{1: 2, 3: 4, 5: 6}

您将如何进行?

最佳答案

将元素 2 两个配对并将结果传递给 dict() :

result = dict(zip(*[iter(values)] * 2))

通过使用 iter()在这里,您避免像 [::2][1::2] 切片那样创建两个内存列表对象。参见 Iterating over every two elements in a list至于为什么会这样。

演示:

>>> values = (1, 2, 3, 4, 5, 6)
>>> dict(zip(*[iter(values)] * 2))
{1: 2, 3: 4, 5: 6}

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

相关文章:

python-3.x - 在 Pandas 中按组均值创建以总均值为中心的变量

python - 在 Pandas 中使用 group by 进行转换

python - 从 Locust 获取单个任务的统计信息

python - 将 Python ISO 日期时间转换为 Epoch

python - 测试 Graphql API - python

python - 如何将包含无法识别的时区的字符串转换为日期时间?

python - Intellij idea 无法正确运行 IPython notebook

python - Django 告诉最后一个项目是否具有双重排序中的某些属性(order_by)

python - matplotlib.pyplot : how to include custom legends when plotting dataframes?

python - ssh 到服务器并使用 Python 执行等效的curl