python - 根据项目列表中元素的顺序从键列表和项目列表创建字典

标签 python list csv dictionary dictionary-comprehension

在查看这个问题后,我发现了解如何使用唯一列表作为项目和单个列表作为键很有帮助:Creating a dictionary with keys from a list and values as lists from another list 但是,我有一些列表,其中列表的第一个、第二个和其他元素需要按该顺序与键列表关联。

问题是我已经尝试了该问题中描述的方法,但在将项目归因于我的字典的键时,它没有考虑主列表中每个列表中元素的顺序。

key_list = ['m.title', 'm.studio', 'm.gross', 'm.year']
col = [['Titanic', '2186.8', 'Par.', '1997'], 
['The Lord of the Rings: The Return of the King', '1119.9', 'NL', '2003']]

我想要一个字典,其中 col 列表的项目根据元素在所有列表中出现的顺序归因于 key_list,并与 key_list 中元素的顺序匹配。

期望输出:{m.title:['泰坦尼克号', '指环王:王者归来'], 'm.studio':['2186.8', '1119.9'], 'm.总计':['Par.', 'NL'], 'm.year':['1997', '2003']}

最佳答案

你可以做dict(zip(...)):

print([dict(zip(key_list,values)) for values in col])

编辑:

print({k:list(zip(*col))[i] for i,k in enumerate(key_list)})

或者@MarkMeyer 的解决方案。

关于python - 根据项目列表中元素的顺序从键列表和项目列表创建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53952880/

相关文章:

python - 创建包含多个记录的数据框

python - 对于列表的每个成员,将其写入单独的文件 python

python - 从两个列表中找到丢失的名字

phpMyAdmin,导入 csv 时文本被截断

python - CSV 写入文件困难

python - 按第一个列表对列表列表进行排序

python - Ubuntu 17.04 上的 OpenCV VideoCapture() 无法正常工作

python - 如何使用 pandas 从 csv 读取多行到单个数据帧行

python - 如何使用 numpy 对角线对角填充矩阵

string - MATLAB 中的整数列表到字符串列表