Skip to main content
 首页 » 编程设计

python之使用来自列表的键和来自另一个列表的列表的值创建字典

2025年05月04日14三少

我有一个 list

key_list = ['m.title', 'm.studio', 'm.gross', 'm.year'] 
cols = [ 
    ['Titanic', 'The Lord of the Rings: The Return of the King', 'Toy Story 3'],  
    ['Par.', 'NL', 'BV'], 
    ['2186.8', '1119.9', '1063.2'], 
    ['1997', '2003', '2010'] 
] 

我想构造一个字典table_dict,其键是key_list的元素,值是cols的各个子列表。

我目前的代码如下:

i = 0 
for key in key_list: 
    table_dict[key] = cols[i] 
    i = i + 1 
 
return table_dict 

我似乎找不到错误,但是当我运行它时我得到:

dict[key] = cols[i] 
IndexError: list index out of range 

请您参考如下方法:

你可以简单地zip键和值并将其传递给 dict。您可以阅读有关构建字典的更多信息 here

print dict(zip(key_list, cols)) 

输出

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