2016-09-18 34 views
0

當我保存表示與格式的圖形的字典:消除由csv.DictWriter創建括號在Python

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

,並與csv.DictWriter保存並加載它,我得到:

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

如何避免爲值列表添加引號或在讀取文件時需要使用哪些代碼來刪除它們?幫助將不勝感激!

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) 

在編輯器中打開CSV文件看起來是這樣的:

vertices,edges 
b,"['a', 'c']" 
a,[] 
c,['a'] 
d,[] 
+1

括號?你的意思是引號/引號? CSV不是適用於嵌套數據結構的格式,因此您已經吠叫錯誤的樹。 – ShadowRanger

+0

使用[JSON而不是CSV](http://stackoverflow.com/questions/17043860/python-dump-dict-to-json-file)並繼續。 CSV設計用於平面表格式數據格式,不適用於任意嵌套數據。使用適當的工具來達到你想要達到的效果。 –

回答

0

你有

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

然後

edges = graph_dict[vertex] 
    writer.writerow({'vertices': vertex, 'edges': edges}) 

這開單的文件 - 它被轉換爲str。

DO,例如

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

這只是在問題上隱藏磁帶,因爲這意味着在您重新讀取時手動解析「真正的CSV內的差CSV」。 – ShadowRanger

0

CSV不用於嵌套的數據結構;它沒有處理它們的有意義的方式(它將您的list值轉換爲str以進行輸出)。

您或者需要使用更合適的格式(例如JSON或pickle),或者使用可怕的黑客將值的repr轉換回其原始值(例如, ast.literal_eval(除非如果一些原始值應該是字符串將無法正常工作)。

0

您試圖使用CSV「序列化」這些數據,如果您想分析Python以外的文件,這可能是適當的。如果不是,您的問題將通過pickle模塊更容易解決。

如果您必須使用CSV,請確保您保存爲文件「邊緣」的值均爲字符串。然後,當你從文件中讀回來時,將它們轉回到列表中。

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 

根據要求給出{'a': [], 'b': ['a', 'c'], 'c': ['a'], 'd': []}

+1

非常感謝您的答案!我沒那麼有經驗,所以感謝提示pickle和json。基本上,我只是想在存儲數據之後存儲數據,並在下次開始時調用保存的數據。另外我想在使用csv(和其他)的gephi中可視化數據。但是當我查看它時,發現有一個json導入程序,所以我的問題得到解決。謝謝! –