'Write csv with more than 2 nested dict

Here is my sample dict:

nested_dict = 
{
  "value1_1": "X",
  "value1_2": {
             "value2_1": "Y",
             "value2_2": {
                       "value3_1": "Z3_1",
                       "value3_2": "Z3_2"
                        ...
                        }
             ...
  }

I want to convert it to a CSV with a similar form:

X,Y,Z3_1,Z3_2

Or with the header but would prefer not having it:

Value1_1,Value2_1,Value3_1,Value3_2
X,Y,Z3_1,Z3_2

I've found some answers with using DictWriter but I couldn't figure it supporting more than 2 nested dict.

Should I write my own csv writer?



Solution 1:[1]

I do not think that you will find a writer doing that. Maybe do something like this?

nested_dict = {
   "value1_1": "X",
   "value1_2": {
       "value2_1": "Y",
       "value2_2": {
           "value3_1": "Z3_1",
           "value3_2": "Z3_2"
       }
   }
}   

def getLatestLevel(dictionary, values=[]):
    for key, item in dictionary.items():
        if type(item) is dict:
            values = getLatestLevel(item, values)
        else:
            values.append(item)
    return values
            

with open("FILE.csv", 'w') as myfile:
    myfile.write(", ".join(getLatestLevel(nested_dict)))

It will write this to FILE.csv:

X, Y, Z3_1, Z3_2

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1