在查看这个问题后,我发现了解如何使用唯一列表作为项目和单个列表作为键很有帮助: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/