[Tutor] extracting information from a complex dict.

mhysnm1964 at gmail.com mhysnm1964 at gmail.com
Sun Jan 31 01:16:29 EST 2021


All,

 

Using windows and python 3.8.

 

I need to convert a complex dict into a list. Then I am saving the list as a
CSV. I know there is more than likely a library which can convert the tree
(dict) into a CSV file. But I want to learn recursive functions. I have
learnt the basics when using maths functions. Thus I understand the basic
logic of recursive functions. Now I am trying to do something more
difficult. 

 

The basic dict structure is:

 

{

    "A": {

        "A A Attanasio": {

            "A A Attanasio": [

                "Wyvern plot.txt",

                "Wyvern.mp3"

            ]

        }

    }

}

 

I extracted the above from a JSON file which the Dict is based upon. Basic
structure:

*	The first dict has a maximum of 26 entereies. A to z. Calling this
level 1.
*	The first child can have an unknown number of dict's. Only dicts
exist at this level. For ease of reading I will call this level 2 dict.

*	Level 2 dicts can have a value of None. Easily tested for.

*	The child of level 2 dict, ease of reading level 3 dict:

*	Level 3 dict's contains a list or
*	Another dict containing another level 3 dict structure using my
convention is Level 4 dict. Nothing is deeper than this.

 

Outcome: I want to build a list that contains the following list structure:

[

              ['a', 'author name', author name', bookt title],

              ['a', 'author name', author name', bookt title]

]

 

This might be easier if there was a parent key / value. But there is not.
The file is to large to manually change this. I would have to write some
code to insert the parent key. I am hoping there is a way not to do that.

 

My logic (thinking) is (starting from the top of the tree and working your
way down):

1.	The following variables need to be passed into the function (I
think):

a.	List containing the above structure that I want.
b.	A list of all the keys used to get to the value which contains the
list.
c.	The current key which either contains another dict or the list.
d.	The First call is the full dict and each call after this point is
the dict for the next level down. Basically popping the dict.

2.	Test the dict value to see if it contains a None. If does, then only
store the first three elements of the array as there is no books titles.
3.	Test the dict value to see if it contains a list. If so, then append
to the above list structure with all values.
4.	If a dict, then add to the key list and only return the dict
contained in the value. 

 

What I am not sure if the above logic will work or if I should be using a
loops within the recursive function. I don't have any code to show as I am
not sure how to start. Done searching and seen examples. Still confused.

 

Hope someone can give me some pointers.

 

Sean 



More information about the Tutor mailing list