簡體   English   中英

刪除由csv.DictWriter在python中創建的括號

[英]remove parentheses created by csv.DictWriter in 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,[]

你有

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

然后

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

這會將列表寫入文件-它將轉換為str。

做,例如

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

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

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

您正在嘗試使用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': []}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM