使用列表中的键创建字典,将值作为另一个列表中的列表创建

时间:2013-12-03 06:39:51

标签: python list dictionary

我有一个清单

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

3 个答案:

答案 0 :(得分:7)

您可以简单地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']}

答案 1 :(得分:1)

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']]
for i in cols:
    print dict(zip(key_list, i))

如果您想要这样的输出

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

答案 2 :(得分:0)

您提供的示例无错误地工作。您的代码中可能存在其他问题。但是,错误消息告诉您的是,

列表cols的索引i超出范围。这意味着当迭代第一个列表(其中包含4个元素,因此迭代4次)时,其他列表cols没有足够的项目 - 意味着可能少于4个。

围绕此问题的工作是指python docs dict

table_dict = dict(zip(key_list, cols))
print table_dict

输出:

{'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']}
相关问题