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

Creating a Dictionary from a Key List and Item List Based on the Order of the Elements in the Item List

在查看这个问题后,我发现了解如何使用唯一列表作为项目并将单数列表用作键很有帮助: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:['Titanic', 'The Lord of the Rings: The Return of the King'], 'm.studio':['2186.8', '1119.9'], 'm.gross' :['Par.', 'NL'], 'm.year':['1997', '2003']}

您要创建的对象列表可以使用嵌套在列表推导中的字典推导来创建:

[{key_list[idx]: val for idx, val in enumerate(row)} for row in col]

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

编辑:

对于 { key: List } 的字典:

dict(zip(key_list, [[row[idx] for row in col] for idx,_ in enumerate(key_list)]))

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

你可以做到 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 的解决方案。

我不确定您是否真的需要列表或者是否可以使用元组。但是如果元组没问题,这非常简洁:

d = dict(zip(key_list, zip(*col)))

结果:

{'m.title': ('Titanic', 'The Lord of the Rings: The Return of the King'),
 'm.studio': ('2186.8', '1119.9'),
 'm.gross': ('Par.', 'NL'),
 'm.year': ('1997', '2003')}