简体   繁体   English

使用列表中的键和其他列表中的值创建字典

[英]Creating a dictionary with keys from a list and values as lists from another list

I have a 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']
]

I want to construct a dictionary table_dict whose keys are the elements of key_list, and values are respective sublists of cols. 我想构造一个字典table_dict,其键是key_list的元素,而值是cols的相应子列表。

My current code is as follows: 我当前的代码如下:

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

return table_dict

I can't seem to find an error, yet when I run it I get: 我似乎找不到错误,但是运行时我得到:

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

You can simply zip the keys and values and pass it to the dict . 您可以简单地压缩键和值并将其传递给dict You can read more about constructing dictionaries here 您可以在此处阅读有关构造字典的更多信息

print dict(zip(key_list, cols))

Output 输出量

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

If You want OUTPUT like this 如果您想要这样的输出

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

The example you provided works without an error. 您提供的示例可以正常运行。 There might be another problem within your code. 您的代码中可能还有另一个问题。 However, what the error message tells you is that, 但是,错误消息告诉您的是,

The index i of list cols is out of bounds. 列cols的索引i超出范围。 Which means while iterating over the first list (which has 4 elements in it, so iterating 4 times) the other list cols does not have enough items - meaning less than 4 probably. 这意味着在迭代第一个列表(其中有4个元素,因此要迭代4次)时,其他列表列没有足够的项目-可能少于4个。

The work around this issue refer to the python docs dict 解决此问题的方法是参考python docs dict

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

Output: 输出:

{'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']}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM