How to convert list of dictionary values in python to a string and write on seprate cells of a csv file?
Question: I want to write a dictionary on a csv file in Python. I want the output to be
like this:

    
    
        key1    key2
         4       3
         2       1
         3
    

but the output is like this:

    
    
        key1    key2
       ['4']   ['3']
       ['2']   ['1']
       ['3']
    

I'm using this code to write dictionary on csv files:

    
    
            my_file_path = os.path.join(filePath, 'MyDictionary.csv')
            with open(my_file_path,'w', newline='') as csv_file:
                csv_writer = csv.DictWriter(csv_file, my_data.keys())
                csv_writer.writeheader()
                csv_writer.writerow(my_data) 
    

I couldn't find my answer in the archive. How can I convert the list of values
in a way that it is written as a string on a csv file?


Answer: Try this:

    
    
    >>> import csv,os
    >>> my_data = {'key1': [4,2,3], 'key2': [3,1]}
    >>> filePath='.'
    >>> my_file_path = os.path.join(filePath, 'MyDictionary.csv')
    >>> with open(my_file_path,'w',, newline = '') as csv_file:
    ...     keys = sorted(my_data.keys()) #ensure key1 is before key2
    ...     csv_writer = csv.writer(csv_file, delimiter=',')
    ...     csv_writer.writerow(keys)
    ...     num_loops = max([len(v) for k,v in my_data.iteritems()])
    ...     for idx in range(0,num_loops):
    ...         row = []
    ...         for k in keys:
    ...             to_append = my_data[k][idx] if len(my_data[k])>idx else ''
    ...             row.append(to_append)
    ...         csv_writer.writerow(row) 
    

Output file:

    
    
    key1    key2
    4       3
    2       1
    3
    

