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>You're trying to "serialize" this data using CSV, which might be appropriate if you want to analyze the file outside of Python. If not, your problem will be solved more easily with the <a href="https://docs.python.org/3/library/pickle.html" rel="nofollow">pickle</a> module.</p>

<p>If you must use CSV, make sure the values you save as "edges" to the file are all strings. Then when you read them back from the file, turn them back to a list.</p>

<pre><code>import csv

graph_dict = {'b': ['a', 'c'], 'a': [], 'c': ['a'], 'd': []}

file_path = 'graph.csv'

with open(file_path, 'w', newline='') as outfile:
    fieldnames = ['vertices', 'edges']
    writer = csv.DictWriter(outfile, fieldnames=fieldnames)
    writer.writeheader()

    for vertex, edges in graph_dict.items():
        # Save multiples as "x,y,z"
        edges = ','.join(edges)
        row = {'vertices': vertex, 'edges': edges}
        writer.writerow(row)

loaded_graph = {}
with open(file_path, 'r', newline='') as infile:
    reader = csv.DictReader(infile)
    for row in reader:
        edges = row['edges']
        # Read empty as [], full as ['x', 'y', 'z']
        edges = edges.split(',') if edges else []
        loaded_graph[row['vertices']] = edges
</code></pre>

<p>That gives <code>{'a': [], 'b': ['a', 'c'], 'c': ['a'], 'd': []}</code> as requested.</p>

python python-3.x