![](/img/trans.png)
[英]How to compare and merge two nested dictionaries into another nested dictionary of lists?
[英]How to merge three lists of dictionaries into one nested dictionary using Python
注意:我通過示例學習,因此提出了這個問題。
因此,我正在嘗試從三 (3) 個字典列表創建一個嵌套字典。 字典列表如下所示:
topic_list = [{"id": 1, "title": "I have no idea.", "slug": "i-have-no-idea"}, ...]
thread_list = [{"id": 1, "title": "I still have no idea.", "author_name": "me", "topic": 1}, ...]
message_list = [{"id": 1, "content": "I really have no clue what I am doing.", "author_name": "me", "thread": 1}, ...]
所以,(我認為)最終結果應該如下所示:
nested_dictionary = [
"topic": {
"id": 1,
"title": "I have no idea.",
"slug": "i-have-no-idea",
"threads": {
"id": 1,
"title": "I still have no idea.",
"author": "me",
"messages": {
"id": 1,
"content": "I really have no clue what I am doing.",
"author_name": "me"
}
}
}
]
基本上,一切都有一個ID。 消息通過線程 id 與線程相關聯,線程通過主題 id 與主題相關聯。
我的問題:
我實際上沒有為此編寫任何代碼,但我假設它需要嵌套循環,首先使用主題 ID 作為鍵將所有線程關聯到適用的主題,然后使用線程 ID 作為鍵將所有消息關聯到適用的線程。
我已經瀏覽了 SO 並執行了大量的谷歌搜索類似的東西。 任何建議和-或指出我正確的方向將不勝感激。
基本上,一切都有一個ID。 消息通過線程 id 與線程相關聯,線程通過主題 id 與主題相關聯。
雖然所有東西都有一個 id,但線程 object 需要一個topic_id
來知道它們應該嵌套在哪個主題中。 同樣,消息需要一個thread_id
(可能也需要一個topic_id
)。
考慮到這一點,您的嵌套字典將如下所示:
nested_dictionary = {
"topics": [
{"id": 5247,
"title": "I have no idea.",
"slug": "i-have-no-idea",
"threads": [
{"id": 9153,
"topic_id": 5247
"title": "I still have no idea.",
"author": "me",
"messages": [
{"id": 1935,
"thread_id": 9153
"content": "I really have no clue what I am doing.",
"author_name": "me"
},
]
},
]
},
]
}
注意:我更改了 id 以使示例更清晰。
1) Insert each topic into nested_dictionary
2) For each thread, iterate over the topics in the nested_dictionary until you find topic[id] == thread[topic_id] and insert the thread into that topic
3) For each message, iterate over the threads in the nested_dictionary until you find thread[id] == message[thread_id]
這代表了最簡單的解決方案。 但是,更好的解決方案是更改架構以使用 id 作為嵌套字典中每個項目的鍵。 這將使您的算法降低到線性時間復雜度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.