将字典列表转换为字典

时间:2019-06-10 15:09:37

标签: python python-3.x elasticsearch

我想将字典列表转换成字典 字典应该是字典列表的精确副本。

我目前将此输出存储在一个变量中,该变量是字典列表-

[{'title': 'some dta', 'author': 'soem dta ', 'responses': 'some data', 'views': 'some dta ', 'lastte': "sommedta", 'last_post_by': 'by In Omnibus'}, {'title':,'Voting',' etc. etc. etc. }] 

并且我希望将其存储到另一个变量中,该变量可以在程序中的任何地方调用

{'title': 'some data ', 'author': 'some data ', 'responses': 'some data ', 'views': '897 views', 'last_post_date': "Sun 28th Aug '16, 7:05am", 'last_post_by': 'by somedata'}, {'key','value','key',value' }, 
{ etc. etc. etc. }

我尝试过此-


dct = {}
for sub_dict in dictionary:
    dct.update(sub_dict)

print(dct) #here the last element of list is printed as dictionary but, I want to store all the data of dictionary in one variable and use it later in the elasticsearch body

数据进入了弹性搜索索引

1 个答案:

答案 0 :(得分:1)

考虑一下:

list_of_articles = [article0, article1, ... article99]

如果您想对某篇文章做某事,就这么简单

article = list_of_articles[22]
dostuff(article)

但是,您所说的是将所有文章(由于某种原因而有所不同)都混在一起。如果它们都具有相同的键,那么您将只看最后一篇文章,但是如果其中一些键具有不同的键,则可以将它们与上一篇文章混在一起。

当然,article可能是一个类,但更可能是一个简单的字典,与您在原始问题中发布的代码完全匹配。直到现在,我都一直试图隐瞒这一点。

注释的附录:从“字典列表”更改为“字典命令”真的很容易,只要它对数据有意义。

dict_of_dict = {article['title']: article for article in list_of_articles}

当然,除非每篇文章都有不同的标题,否则这将失败。如果您实际上没有使用标题进行查找(至少是我的看法),它将不如list_of_articles。

相关问题