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

2024-03-28 11:02:49 发布

您现在位置:Python中文网/ 问答频道 /正文

在看了这个问题之后,我发现了解如何使用唯一列表作为项和单数列表作为键是很有帮助的: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\u列表,并与key\u列表中元素的顺序匹配。你知道吗

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


Tags: ofthekeyfrom元素列表字典顺序
3条回答

可以使用嵌套在列表理解中的Dict理解创建要创建的对象列表:

[{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')}

相关问题 更多 >