Python 如何将下列列表转换为字典?

Python 如何将下列列表转换为字典?,python,list,dictionary,Python,List,Dictionary,我有这样一份清单: [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']] {'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']} list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one

我有这样一份清单:

[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}
list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
dict_from_list = dict(zip(list_of_list[0], zip(*list_of_list[1:])))
我想将此列表转换为字典,如下所示:

[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}
list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
dict_from_list = dict(zip(list_of_list[0], zip(*list_of_list[1:])))
如何做这样的事情?

试试这个:

dict(zip(xs[0], zip(*xs[1:])))
对于作为dict值的列表:

dict(zip(xs[0], map(list, zip(*xs[1:]))))

您可以使用内置的zip功能轻松执行以下操作:

[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}
list_of_list = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
dict_from_list = dict(zip(list_of_list[0], zip(*list_of_list[1:])))
在这种情况下,内部zip(*list_of_list[1:])将列表列表从list_of_list(第一个元素除外)转换为元组列表。元组保持顺序,并再次使用假定的键压缩以形成元组列表,该列表通过dict函数转换为适当的字典

请注意,这将使用tuple作为字典中值的数据类型。根据您的示例,一个班轮将给出:

{'ok.txt': (10, 'first_one', 'done'), 'hello': (20, 'second_one', 'pending')}
为了有一个列表,您必须使用list函数映射内部zip。 (即)变化

有关zip函数的信息,请单击


编辑:我刚刚注意到答案和西蒙给出的答案是一样的。当我在终端中尝试代码时,Simon给出的速度快得多,而我在发布时没有注意到他的答案。

检查:严格来说,这不会创建列表,而是创建元组。第一个是完美的@BurhanKhalid
tuple
s,很可能足以在使用其他人的代码时提供属性。谢谢