python - 将 Python 列表值映射到字典值

标签 python

我有一个行列表...

行数 = [2, 21]

还有一个数据字典...

data = {'x': [46, 35], 'y': [20, 30]}

我想构建第二个字典,dataRows,以如下所示的行为键...

dataRows = {2: {'x': 46, 'y': 20}, 21: {'x': 35, 'y': 30}}

我尝试了以下代码,但 dataRows 的值始终相同(循环中的最后一个值):

for i, row in enumerate(rows):
    for key, value in data.items():
        dataRows[row] = value[i]

如有任何帮助,我们将不胜感激。

最佳答案

您的问题是您没有将子词典放入数据行中。修复方法是这样的:

for i, row in enumerate(rows):
    dataRows[row] = {}
    for key, value in data.items():
        dataRows[row][key] = value[i]

关于python - 将 Python 列表值映射到字典值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39955222/

相关文章:

python 3.5 类型提示 : can i check if function arguments match type hints?

python - 如何以及在何处格式化 Django(Python、Ajax)中的日期?

python - 无法使用 SIGKILL 杀死 docker 容器内的 pid 1

python - 3d 随机采样

python - 对字典进行排序-声明 python 的顺序

python - 在循环中切片 NumPy 数组

python - 谷歌应用引擎模块 - 长时间运行的任务 > 10 分钟

python - Pycharm 更新到 2016.2 后导入 RuntimeWarning

python - conda 可以全局安装包还是所有包都安装到特定环境?

jquery - 使用ajax和flask来更新表