简体   繁体   中英

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.

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 . 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. 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.

The work around this issue refer to the 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']}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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