繁体   English   中英

如何将以下列表转换成字典?

[英]How to convert the following lists into dictionary?

我有一个这样的清单:

[['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]

我想将此列表转换成字典,像这样:

{'ok.txt' : ['10', 'first_one', 'done'], 'hello' : ['20', 'second_one', 'pending']}

怎么做这样的事情?

尝试这个:

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

对于列表作为dict的值:

dict(zip(xs[0], map(list, zip(*xs[1:]))))
>>> lis  = [['ok.txt', 'hello'], [10, 20], ['first_one', 'second_one'], ['done', 'pending']]
>>> keys, values = lis[0],lis[1:]
>>> {key:[val[i] for val in values] 
                                  for i,key in enumerate(keys) for val in values}
{'ok.txt': [10, 'first_one', 'done'], 'hello': [20, 'second_one', 'pending']}

您可以使用内置的zip函数轻松地执行此操作,如下所示:

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函数将其转换为适当的字典。

请注意,这将具有元组作为字典中值的数据类型。 根据您的示例,单线将给出:

{'ok.txt': (10, 'first_one', 'done'), 'hello': (20, 'second_one', 'pending')}

为了拥有列表,您必须使用list函数映射内部zip。 (即)变化

zip(*list_of_list[1:]) ==> map(list, zip(*list_of_list[1:]))

有关zip功能的信息,请单击此处

编辑:我只是注意到答案与西蒙给出的答案相同。 当我在终端中尝试代码时,Simon给出了更快的速度,而在发布时我没有注意到他的回答。

暂无
暂无

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

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