def save_dict_to_CSV(dict_data, dest_file="output.csv", headers=None, col_separator=","): f = open(dest_file, "w+") fcsv = csv.writer(f) if headers is None and len(dict_data) > 0 and type(dict_data[list(dict_data.keys())[0]]) is dict: flattened_first = list(FormatHelpers.flatten(dict_data[list(dict_data.keys())[0]], True).keys()) headers = ["local_path"] + flattened_first if headers is not None: fcsv.writerow(headers) for first_col, cols in dict_data.items(): cols = [first_col] + [str(col) for col in list(FormatHelpers.flatten(cols,flatten_list=True).values())] fcsv.writerow(cols) f.close()
def test_flatten(self): dummy_dict = {"a":1, "b":2, "c":{"A":1,"B":2,"C":["a","b","c"],"D":{"un":1, "deux": 2}}} flattened_dummy_dict = FH.flatten(dummy_dict) self.assertEqual(flattened_dummy_dict["deux"], dummy_dict["c"]["D"]["deux"]) self.assertEqual(flattened_dummy_dict["b"], dummy_dict["b"]) self.assertEqual(flattened_dummy_dict["C"], dummy_dict["c"]["C"])