簡體   English   中英

如何使用 Python 將三個字典列表合並為一個嵌套字典

[英]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 與主題相關聯。

我的問題:

  1. 我知道嵌套字典的格式不正確,但至少對於我要完成的工作有意義嗎?
  2. 有人在 Python 中看到過這樣的例子嗎?

我實際上沒有為此編寫任何代碼,但我假設它需要嵌套循環,首先使用主題 ID 作為鍵將所有線程關聯到適用的主題,然后使用線程 ID 作為鍵將所有消息關聯到適用的線程。

我已經瀏覽了 SO 並執行了大量的谷歌搜索類似的東西。 任何建議和-或指出我正確的方向將不勝感激。

  1. 我認為您在示例中使用的 id 可能是造成混淆的根源。

基本上,一切都有一個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. 假設上述模式是正確的,那么您對嵌套 for 循環的直覺是正確的。 我會想象這樣一個算法看起來像:
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.

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