如何利用键列表从非均匀嵌套列表生成字典列表?字典推导式尝试失败
嵌套列表转字典列表的解决办法
你需要把嵌套结构的value_list转换成由字典组成的列表,每个字典的键对应key_list中的内容。之前用的字典推导式没达到预期,问题出在错误地对整个value_list做切片操作,而非逐个处理里面的单条新闻数据。
输入示例
value_list = [ ['this is news head', 'abstract of the news', 'link of the news', ['title1', 'title2', 'title3', 'title10']], ['this is news head2', 'abstract of the news2', 'link of the news2', ['title1', 'title2', 'title3', 'title10']] ] key_list = ['head', 'abstract', 'link', 'titles']
正确解法
用列表推导式遍历value_list里的每一组数据,通过zip把key_list和单组数据的元素一一对应,最后转成字典即可:
result = [dict(zip(key_list, item)) for item in value_list]
验证结果
运行上述代码后,就能得到你预期的输出:
[ {'head':'this is news head', 'abstract':'abstract of the news', 'link': 'link of the news', 'titles': ['title1', 'title2', 'title3','title10']}, {'head':'this is news head2', 'abstract':'abstract of the news2', 'link': 'link of the news2', 'titles': ['title1', 'title2', 'title3','title10']} ]
原代码问题说明
你之前写的{k: value_list[i::3][i::10] for i, k in enumerate(key_list)},错误地从整个value_list层面切片取值,但value_list里的每个子元素才是对应一个字典的完整数据,这种切片逻辑完全偏离了目标数据结构,自然得不到正确结果。
内容的提问来源于stack exchange,提问作者H_Yilmaz
相关产品推荐
相关产品推荐

