亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

TypeError: {'name:busi,group:1'} 在 python 中從頭開始構建

TypeError: {'name:busi,group:1'} 在 python 中從頭開始構建

慕無忌1623718 2021-10-26 16:10:47
我們如何通過使用csv數據或作為列表提供的數據在python中動態創建json文件data.csv 看起來像這樣busi,bizthank,pumpthank,suchthank,merri它顯示了圖中節點之間的鏈接/邊。我正在嘗試構建節點和數組的 json,但出現 json 序列化錯誤。nodes = []nodes_dict = {}counter = 0edges = open(edges_file)    for line in edges:        line = line.replace("\n","")        source =  line.split(",")[0]        target = line.split(",")[1]        if source not in nodes_dict:            node_arr = {"name:" + source  + "," + "group:1"}            nodes.append(node_arr)            nodes_dict[source] = counter            counter += 1        if target not in nodes_dict:            node_arr = {"name:"+ target + "," + "group:1"}            nodes.append(node_arr)            nodes_dict[target] = counter            counter += 1 json.dumps(nodes,outputfile)但我收到此錯誤類型錯誤:{'name:busi,group:1'} 不是 JSON 可序列化的我想要的輸出 "nodes":[    {"name":"Myriel","group":1},        {"name":"Napoleon","group":1},{"name":"Mme.Hucheloup","group":8}],"links":            [{"source":1,"target":0,"value":1},{"source":2,"target":0,"value":8},                {"source":3,"target":0,"value":10},{"source":3,"target":2,"value":6}}}
查看完整描述

1 回答

?
開滿天機

TA貢獻1786條經驗 獲得超13個贊

你正在構建你的 dict 錯誤。


嘗試這樣的事情


nodes = []

nodes_dict = {}

counter = 0

edges = open(edges_file)

    for line in edges:

        line = line.replace("\n","")

        source =  line.split(",")[0]

        target = line.split(",")[1]

        if source not in nodes_dict:

            node_arr = dict(

                name=source,

                group=1

            )

            nodes.append(node_arr)

            nodes_dict[source] = counter

            counter += 1


        if target not in nodes_dict:

            node_arr = dict(

                name=target,

                group=1

            )

            nodes.append(node_arr)

            nodes_dict[target] = counter

            counter += 1

 json.dumps(nodes,outputfile)


查看完整回答
反對 回復 2021-10-26
  • 1 回答
  • 0 關注
  • 245 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號