remove parentheses created by csv.DictWriter in python
<p>when i'm saving a dictionary representing a graph with the format:</p>

<pre><code>graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []}
</code></pre>

<p>and save it with the csv.DictWriter and load it i get:</p>

<pre><code>loaded_graph ={'b': "['a', 'c']", 'c': "['a']", 'a': '[]', 'd': '[]'}
</code></pre>

<p>How  can i avoid the added quotation marks for the value lists or what code do i have to use to remove them when reading the file? Help would be appreciated!</p>

<pre><code>print(graph_dict)

with open('graph.csv', 'w') as csvfile:

    graph = ['vertices', 'edges']
    writer = csv.DictWriter(csvfile, fieldnames=graph)

    writer.writeheader()

    for vertex in graph_dict:
        edges = graph_dict[vertex]

        writer.writerow({'vertices': vertex, 'edges': edges})


print("reading")

loaded_graph = {}

with open('graph.csv') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        loaded_graph[row['vertices']] = row['edges']

print(loaded_graph)
</code></pre>

<p>the csv file opened in editor looks like this:</p>

<pre><code>vertices,edges
b,"['a', 'c']"
a,[]
c,['a']
d,[]
</code></pre>

<p>CSV is not intended for nested data structures; it has no meaningful way of dealing with them (it's converting your <code>list</code> values to <code>str</code> for output).</p>

<p>You either need to use a more appropriate format (e.g. JSON or <code>pickle</code>), or use horrible hacks to convert the <code>repr</code> of the values back to their original values, e.g. <a href="https://docs.python.org/3/library/ast.html#ast.literal_eval" rel="nofollow"><code>ast.literal_eval</code></a> (except that won't work properly if some of the original values were supposed to be strings).</p>

python python-3.x