Python Forum

Full Version: Transform simplified dictionary to nested dictionaries
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Today, I was trying to solve a question in which the data is structured like:
{
  "bar": [
    {
      "id": 1,
      "foo_id": 1,
      "title": "bar title 1"
    },
    ...
  ],
  "foo": [
    {
      "id": 1,
      "title": "foo title 1"
    },
    {
      "id": 2,
      "title": "foo title 2"
    },
    ...
  ],
  "baz": [
    {
      "id": 1,
      "bar_id": 1,
      "title": "baz title 1"
    },
    ...
  ]
}
And it should be transformed in this format (no id, foo_id, bar_id will be included):
{
  "foo title 1": [
    {
      "bar title 1": [
        {
          "final": "baz title 1", // take baz title as "final"
          "query": "done" // this is always done
        },
        ...
      ],
      ...
    },
    ...
  ],
  ...
}
The dictionary of bar list matches with the dictionary of foo list. The dictionary of baz list matches with the dictionary of bar list.

And I solved this with a lot of for loops and with more than 30 lines of code. But I think this can be solved with no more than 2 loops. I'll be glad to see the code shorter as far as possible.

Your help will let me learn to code in better way. And also, what kind of articles, posts, sites to practice on, should I read more for improving my skill on data structures.

Thanks.
It looks like three loops to me. First loop through the foos, adding the title and an empty list to the master dictionary. Then loop through the bars, appending a dictionary (with the title and an empty list) to the list in the appropriate foo. In this loop you also need to keep track of another dictionary of bar ids to foos (the title keys in the master dictionary). Finally, loop through the bazes, adding them to the appropriate master[foo][bar] list, using your dictionary of bars to foos.