簡體   English   中英

將字典列表轉換為字典

[英]Convert list of dictionaries to dictionaries

我想將字典列表轉換為字典,並且字典應該是字典列表的精確副本。

我目前將此輸出存儲在一個變量中,該變量是字典列表-

[{'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

數據進入了彈性搜索索引

考慮一下:

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。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM