【问题标题】:Creating a dictionary with keys from a list and values as lists from another list使用列表中的键和值作为另一个列表中的列表创建字典
【发布时间】:2013-12-03 06:39:51
【问题描述】:

我有一个清单

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

【问题讨论】:

  • 请向我们展示完整的堆栈跟踪。
  • 我想您在某处将 table_dict 初始化为 table_dict = dict()?
  • @AndreiBoyanov 啊,就是这样,谢谢!

标签: python list dictionary


【解决方案1】:

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

【讨论】:

  • 同意,不过我可能会提出 len(key_list) == len(cols) 的断言。
【解决方案2】:
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'}

【讨论】:

    【解决方案3】:

    您提供的示例没有错误。您的代码中可能还有另一个问题。但是,错误消息告诉您的是,

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

    解决此问题的方法请参阅 python 文档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']}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2021-07-12
      • 2023-01-26
      • 2016-10-05
      • 1970-01-01
      • 2018-01-14
      • 2015-01-17
      相关资源
      最近更新 更多