使用列表中的键和其他列表中的值创建字典 [英] Creating a dictionary with keys from a list and values as lists from another list

查看:64
本文介绍了使用列表中的键和其他列表中的值创建字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单

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 want to construct a dictionary table_dict whose keys are the elements of key_list, and values are respective sublists of cols.

我当前的代码如下:

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

推荐答案

您只需 zip 键和值,并将其传递给dict.您可以在此处

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

输出

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

这篇关于使用列表中的键和其他列表中的值创建字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆